目次
インストール
pip install djangorestframework
settings.py
INSTALLED_APPS = [
...
'rest_framework',
]
ModelをJsonにするSerializerを定義
serializers.py
from rest_framework import serializers
from .models import MyModel
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = '__all__' # ['name', 'age'] ←とかができる
APIを定義
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import MyModel
from .serializers import MyModelSerializer
class MyModelCreateAPIView(APIView):
def post(self, request, format=None):
serializer = MyModelSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
よりシンプルなAPI作成、参照、更新、削除のようなものの場合はViewSetを使った方がシンプルにできる
らしいが、今回は使わなかったので、省きます。
URLを設定
urls.py
from django.urls import path
from .views import MyModelCreateAPIView
urlpatterns = [
path('mymodel/create/', MyModelCreateAPIView.as_view(), name='mymodel-create'),
]
csrfを有効にする
グローバルの設定
settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
}
ひとつずつ設定したい場合
from rest_framework.authentication import SessionAuthentication
class MyModelCreateAPIView(APIView):
authentication_classes = [SessionAuthentication]
…
デバッグ画面みたいなのではなく、JSONで返す方法
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}