Building APIs with Django and Django Rest Framework (readthedocs.org)
Views and Generic Views
목표 : APIView, generics.ListCreateAPIView 이용해서 views.py 완성하기
Creating Views with APIView
from rest_framework.views import APIView
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from .models import Poll, Choice
from .serializers import PollSerializer
class PollList(APIView):
def get(self, request):
polls = Poll.objects.all()[:20]
data = PollSerializer(polls, many=True).data
return Response(data)
class PollDetail(APIView):
def get(self, request, pk):
poll = get_object_or_404(Poll, pk=pk)
data = PollSerializer(poll).data
return Response(data)
APIView를 이용해서 PollList, PollDetail 뷰 클래스를 작성해준다.
from django.urls import path
from .apiviews import PollList, PollDetail
urlpatterns = [
path("polls/", PollList.as_view(), name="polls_list"),
path("polls/<int:pk>/", PollDetail.as_view(), name="polls_detail")
]
이것만으로도 벌써 Get API를 사용할 수 있다.
Using DRF generic views to simplify code
from rest_framework import generics
from .models import Poll, Choice
from .serializers import PollSerializer, ChoiceSerializer, VoteSerializer
class PollList(generics.ListCreateAPIView):
queryset = Poll.objects.all()
serialzier_class = PollSerializer
class PollDetail(generics.RetrieveDestroyAPIView):
queryset = Poll.objects.all()
serializer_class = PollSerializer
코드 재사용성을 높여주는 DRF generic view
이제 Get 뿐만 아니라 Post 기능도 할 수 있다.
More generic views
POST 사용법은 위와 같다.
from rest_framework import generics
from .models import Poll, Choice
from .serializers import PollSerializer, ChoiceSerializer, VoteSerializer
class PollList(generics.ListCreateAPIView):
queryset = Poll.objects.all()
serializer_class = PollSerializer
class PollDetail(generics.RetrieveDestroyAPIView):
queryset = Poll.objects.all()
serializer_class = PollSerializer
class Choicelist(generics.ListCreateAPIView):
queryset = Choice.objects.all()
serializer_class = ChoiceSerializer
class CreateVote(generics.CreateAPIView):
serializer_class = VoteSerializer
Choice, Vote에 대한 View 클래스도 완성해주었다.
from django.urls import path
from .apiviews import PollList, PollDetail, ChoiceList, CreateVote
urlpatterns = [
path("polls/", PollList.as_view(), name="polls_list"),
path("polls/<int:pk>/", PollDetail.as_view(), name="polls_detail"),
path("choices/", ChoiceList.as_view(), name="choice_list"),
path("vote/", CreateVote.as_view(), name="create_vote"),
]
- queryset
- serializer_class
- ListCreateAPIView : GET, POST용도
- RetrieveDestroyAPIView : GET, DELETE용도
- CreateAPIView : POST
Next steps
- simplify API
- URL design
'Computer Science > BackEnd' 카테고리의 다른 글
Django for APIs | #0 Introduction (0) | 2022.09.18 |
---|---|
Django API #5 | More views and viewsets (0) | 2022.09.12 |
Django API #3 | Serializing and Deserializing Data (0) | 2022.09.11 |
장고 DRF #6 | Django REST framework ViewSets & Routers (0) | 2022.09.11 |
장고 DRF #5 | Django REST framework Relationships & Hyperlinked APIs (0) | 2022.09.10 |