Sunday, 26 April 2015

Django REST Framework - Going in depth

In the previous post, Django REST Framework - CRUD, we have used some ready made features of Django REST Framework (DRF) to build REST services. These are implemented internally by DRF and do not provide much customization control over the code behavior.

This post deals with writing each method in a class based view to handle user interaction for different HTTP methods. The view classes will inherit APIView. 

APIView is a view class provided by DRF which inherits Django's View class. The advantage is that it wraps Django's HttpRequest  into DRF's request object and then passes it to the handler methods of the view class. Another benefit is that it appropriately handles the response format by setting the correct render. 

The following views.py snap illustrates code for Book model, similarly code for Author model can be constructed.

from django.http import Http404
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from library.models import Book
from library.serializers import BookSerializer


class BookList(APIView):
    """
    List all books, or create a new book.
    """

    def get(self, request, format=None):
        books = Book.objects.all()
        serializer = BookSerializer(books, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = BookSerializer(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)


class BookDetails(APIView):
    """
    Retrieve, update or delete a book
    """

    def get_object(self, pk):
        try:
            return Book.objects.get(pk=pk)
        except Book.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        book = self.get_object(pk)
        book = BookSerializer(book)
        return Response(book.data)

    def put(self, request, pk, format=None):
        book = self.get_object(pk)
        serializer = BookSerializer(book, data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        book = self.get_object(pk)
        book.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

No comments:

Post a Comment

Your comments are very much valuable for us. Thanks for giving your precious time.