Django REST Framework provides multiple levels of abstraction for handling HTTP requests. APIView, GenericAPIView, and ViewSet help developers build APIs ranging from fully customized logic to fully automated CRUD endpoints.
APIView is the base DRF class where you manually define HTTP methods.
# Simple APIView handling GET request
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class HelloWorld(APIView):
def get(self, request):
return Response({"message": "Hello, World!"}, status=status.HTTP_200_OK)
GenericAPIView builds on APIView and works with mixins for common operations.
# Generic views using built-in CRUD mixins
from rest_framework import generics
from .models import Book
from .serializers import BookSerializer
class BookListView(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
class BookDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
ViewSet groups all CRUD operations into a single class and works with routers.
# ModelViewSet handling full CRUD automatically
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
# Registering ViewSet with DRF router
from rest_framework.routers import DefaultRouter
from .views import BookViewSet
router = DefaultRouter()
router.register(r'books', BookViewSet)
urlpatterns = router.urls
Client ➜ Router ➜ ViewSet ➜ Serializer ➜ Response
Select a view type to see the code reduction vs. the JSON response.