こちらのチュートリアル(1-3章)をやった個人的記録。(要約ではなくメモ)
Tutorial 1: Serialization
- 必要なのは
urls.py,api.py,views.py,models.py,serializer.py - Serialization APIはDjango's Forms APIに似ている
- SerializerクラスはModelSerializerを継承することで簡単に書ける
Modelの属性に含まれない要素をSerializeの際に含めることは可能、例えば
Modelにおいて
- Snippet ModelはUser属性をもつ (Snippet -> Userのbelongs toは指定されている)
- User ModelはSnippet属性をもたない。(User -> Snippetのhas manyは指定されていない)
この時、ModelSerializerにおいて
- SnippetSerializerはuser属性を
serializers.ReadOnlyField(source='user')で - UserはUserSerializerをsnippetを
serializers.PrimaryKeyRelatedField()で引っ張ってくる。
Tutorial 2: Requests and Responses
この章ではfunction based view(@api_viewデコレータ)の実装。
-
return Response(data)を使えばcontent negotiation(determine the correct content type to return to the client)が簡単に実現できる。 - APIendpointに拡張子をつける方法
snippets/views.py
def snippet_list(request, format=None):
snippets/urls.py
urlpatterns = format_suffix_patterns(urlpatterns)
- クライアントからのformatの指定は
HTTP request bodyのAccept:xxx/yyyかendpointの拡張子で行う。
# Request JSON
http http://127.0.0.1:8000/snippets/Accept:application/json
# Request HTML
http http://127.0.0.1:8000/snippets/ Accept:text/html
# JSON suffix
http http://127.0.0.1:8000/snippets.json
# Browsable API suffix
http http://127.0.0.1:8000/snippets.api
(要確認)html = apiっぽい
Tutorial 3: Class based views
この章ではClass-based Views(APIViewを継承)で実装していく。3段階にかけてどんどん楽に実装する方法を学んだ。
-
APIViewを継承- この時点ではrequest method一つにつき一つのmethodを用意する。
-
generics.GenericAPIViewとmixins.XxxxModelMixinを継承.- Xxxx = { ListModelMixin, Create, Retrieve, Update, Destroy}
-
generics.ListCreateAPIViewを継承。
結果、ここまでシンプルになった。
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import generics
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
