Request Object

REST framework introduces a Request object that extends the regular HttpRequest, and provides more flexible request parsing.

The core functionality of the Request object is the request.data attribute, which is similar to request.POST, but more useful for working with Web APIs.

  • request.POST
    • Only handles form data.
    • Only works for 'POST' method.
  • request.data
    • Handles arbitrary data.
    • Works for ‘POST’, ‘PUT’ and ‘PATCH’ methods.

Response Object

REST framework also introduces a Response object, which is a type of TemplateResponse that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.

  • return Response(data)
    • Renders to content type as requested by the client

DRF providestwo wrappers to write API views.

  • @api_view
    • The @api_view decorator for working with function based views.
    • from rest_framework.decorators import api_view
  • APIView
    • The APIView class for working with class-based views.
    • from rest_framework.views import APIView

Function based views

# snippets/views.py
@api_view(['GET', 'POST'])
def snippet_list(request, format=None):
    if request.method == 'GET':
        ...
        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, format=None):
    if request.method == 'GET':		# GET/PUT/DELETE
        ....

More

  • request
    • request used here are not Django obj it is Django-rest obj
  • status=status.HTTP_404_NOT_FOUND
    • can use “404” directly
  • PUT VS PATCH
    • In request.method == ‘PUT’
      • We need to pass all fields
      • SnippetSerializer(snippet, data=request.data)
    • But in request.method == ‘PATCH’
      • We don't need to pass all fields
      • SnippetSerializer(snippet, data=request.data, partial=True)

Reference