Django REST framework
Requests and Responses
Request objects
- request.POST
- handles from data.
- request.data
- handles arbitrary data
Response objects
- return Response(data)
- renders to content type
Status codes
- HTTP 상태 코드를 숫자로 표현하기보다는 HTTP_400_BAD_REQUEST 식별자를 사용하는 편이 좋다.
Wrapping API views
REST 프레임워크에서 API뷰를 작성하는 두 개의 래퍼가 있다.
- @api_view
- 함수 기반 뷰로 작업하기 위한 데코레이터
- APIView
- 클래스 기반 뷰로 작업하기 위한 클래스
- 래퍼는 입력이 잘못되었을 경우 예외 처리 등을 해준다.
Pulling it all together
from urllib import response
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
@api_view(['GET', 'POST'])
def snippet_list(request):
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = SnippetSerializer(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_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request, pk):
try:
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = SnippetSerializer(snippet)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = SnippetSerializer(snippet, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
이제 더이상 반환 객체를 구체적으로 정의해주지 않고,
Response만 해준다.
Adding optional format suffixes to our URLs
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
urlpatterns = [
path('snippets/', views.snippet_list),
path('snippets/<int:pk>/', views.snippet_detail),
]
urlpatterns = format_suffix_patterns(urlpatterns)
'Computer Science > BackEnd' 카테고리의 다른 글
장고 DRF #5 | Django REST framework Relationships & Hyperlinked APIs (0) | 2022.09.10 |
---|---|
장고 DRF #3 | Django REST framework Class-based Views (0) | 2022.09.09 |
장고 DRF #1 | Django REST framework Serialization (0) | 2022.09.09 |
장고 DRF #0 | Django REST framework 튜토리얼 (0) | 2022.09.09 |
Django API #2 | A simple API with pure Django (0) | 2022.09.08 |