Computer Science/BackEnd
Django API #2 | A simple API with pure Django
토마토.
2022. 9. 8. 17:31
Building APIs with Django and Django Rest Framework (readthedocs.org)
The endpoints and the URLS
만들고자 하는 API는 다음과 같다.
- GET /polls/
- Poll의 리스트를 가지고오는 API
- GET /polls/<id>/
- 지정한 id의 Poll을 가지고오는 API
connecting urls to the views
polls 앱에 views.py 파일로 polls_list 뷰와 polls_detail 뷰를 만들어준다.
from django.shortcuts import render
# Create your views here.
def polls_list(request):
pass
def polls_detail(request, pk):
pass
그 다음에 polls 뷰 앱에 매핑해주는 urls.py 파일을 완성해준다.
from django.urls import path
from .views import polls_list, polls_detail
urlpatterns = [
path('polls/', polls_list, name="polls_list"),
path('polls/<int:pk>/', polls_detail, name="polls_detail")
]
writing the views
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from .models import Poll
# Create your views here.
def polls_list(request):
MAX_OBJECTS = 20
polls = Poll.objects.all()[:MAX_OBJECTS]
data = {'results':list(polls.values('question', 'created_by__username', 'pub_date'))}
return JsonResponse(data)
def polls_detail(request, pk):
poll = get_object_or_404(Poll, pk=pk)
data = {'question':poll.question,
'created_by':poll.created_by.username,
'pub_date':poll.pub_date}
return JsonResponse(data)
- polls_list 매소드에서는
- Poll.objects.all()로 모든 객체를 불러온 뒤에, MAX_OBJECTS 사이즈만큼 자른다
- 그 다음 data의 형태로 정렬해서 JsonResponse를 돌려준다.
- 이때 JsonResponse는 json 타입으로 돌려주는 HttpResponse의 일종
using the API
이렇게 get API를 호출할 수 있게 되었다.
why do we need DRF?
DRF은 Django Rest Framework의 약자.
그냥도 API를 개발하는 것이 가능하지만, DRF를 쓰면 API를 개발할 때 사용하는 access control, serialization, rate limiting 등을 간편하게 구현할 수 있게 된다.