Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 77 ยท REST APIs

Django REST Framework Overview

Understand Django REST Framework: serializers, APIView, ViewSets, routers, permissions, authentication and pagination, with runnable plain-Python stand-ins.

You can build a whole API with plain Django views, as the last two lessons showed. You will also notice how repetitive it gets: every endpoint parses JSON, validates fields, converts models to dictionaries, checks permissions and paginates. Django REST Framework (DRF) is the most popular package that packages those chores into reusable parts.

DRF is a third-party library, not part of Django, and it needs a few of its own settings and apps. This lesson is therefore a guided tour. The real DRF code appears in read-only blocks, and two live examples rebuild the core ideas (a serializer and a ViewSet with a router) in about a hundred lines of plain Python, so you can see exactly what the framework does for you.

The building blocks

DRF has a handful of concepts that map onto the pieces you already know:

DRF concept Replaces in plain Django Job
Serializer as_dict() helpers and manual validation Converts objects to JSON-ready data and validates incoming data
APIView / generic views function views with if request.method Class-based views with content negotiation and error handling
ViewSet several related views One class for list, create, retrieve, update and delete
Router hand-written path() entries Generates URLs from a ViewSet
Permission classes decorators like our require_token Declarative access rules
Authentication classes token lookup code Identify who is calling
Pagination classes slicing and counts Shared pagination response format
flowchart LR
    R["Request"] --> A["Authentication<br/>who are you?"]
    A --> P["Permissions<br/>may you?"]
    P --> V["View / ViewSet<br/>action method"]
    V --> S["Serializer<br/>validate / convert"]
    S --> M["Model / ORM"]
    V --> O["Response<br/>(paginated)"]

A DRF request passes authentication and permission checks before the view calls a serializer to validate input or format output.

Serializers: the heart of DRF

A serializer describes the public shape of a resource. It does two jobs in opposite directions:

  • Output: turn a model instance (or a queryset) into plain data such as dictionaries and lists, ready to render as JSON.
  • Input: take untrusted request data, validate it field by field, and give you clean validated_data or a dictionary of errors.

In real DRF a ModelSerializer builds its fields from a model:

Python
# books/serializers.py (real DRF, read-only)
from rest_framework import serializers
from .models import Book


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ["id", "title", "pages", "author"]
        read_only_fields = ["id"]

    def validate_pages(self, value):
        if value <= 0:
            raise serializers.ValidationError("Pages must be positive.")
        return value

The method validate_<field> mirrors the form validation you saw in Form Validation; a method called validate() checks rules that involve several fields together. Compare this with writing the as_dict function and the try/except checks by hand for every endpoint.

To see what a serializer does under the hood, the next example builds a miniature one. Fields convert and validate values, a metaclass collects the declared fields (the same trick Django forms and models use), and is_valid() fills either validated_data or errors.

Python A tiny serializer built from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the five results. The string "474" was converted to the integer 474, a missing optional field received its default, and the field-level problems were all reported together. The last payload passes the field checks but fails the cross-field validate() method. Notice also that for the third payload the validate() step never ran, because field errors came first. The real DRF behaves the same way, and its ModelSerializer also adds create() and update() methods that save to the database.

Views: from APIView to ViewSets

DRF offers views at several levels of convenience. You pick the lowest level that stays readable.

APIView is the base class. It looks like a Django class-based view (see Class-Based Views) but with DRF's Request, Response, authentication and error handling:

Python
# read-only
from rest_framework.views import APIView
from rest_framework.response import Response


class BookList(APIView):
    def get(self, request):
        books = Book.objects.all()
        return Response(BookSerializer(books, many=True).data)

    def post(self, request):
        serializer = BookSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=201)

request.data already contains parsed JSON, form data or multipart data, whatever the client sent, and raise_exception=True turns validation errors into a 400 response automatically.

Generic views (ListCreateAPIView, RetrieveUpdateDestroyAPIView, ...) are the API cousins of Django's generic views. You set queryset and serializer_class and the behavior comes for free.

ModelViewSet goes furthest: one class gives you list, create, retrieve, update, partial update and destroy.

Python
# read-only
from rest_framework import viewsets


class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.select_related("author")
    serializer_class = BookSerializer

Routers generate the URLs

A ViewSet does not map to URLs by itself, because one class handles many URLs. A router inspects the ViewSet and registers the collection and member routes for you:

Python
# read-only
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register("books", BookViewSet)
urlpatterns = router.urls

That produces books/ (list and create) and books/<pk>/ (retrieve, update, delete), with route names book-list and book-detail, plus a browsable API root. The upcoming example builds the same machinery in miniature: a ViewSet that dispatches on the HTTP method and a router that registers two URL patterns.

Permissions, authentication and pagination

These three are configured declaratively, either per view or globally in settings.

Authentication classes answer "who is calling?" DRF includes session authentication (browser logins), basic authentication, and token authentication (Authorization: Token <key>). Token-based JWT support lives in separate packages. If no class recognizes the credentials, the user is anonymous.

Permission classes answer "is this allowed?" Built-ins include AllowAny, IsAuthenticated, IsAdminUser and IsAuthenticatedOrReadOnly. You can combine them and write your own by implementing has_permission(request, view) and optionally has_object_permission(request, view, obj).

Pagination classes such as PageNumberPagination and LimitOffsetPagination wrap list responses in a consistent envelope with count, next, previous and results.

A typical global configuration looks like this:

Python
# settings.py (read-only)
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.TokenAuthentication",
    ],
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticatedOrReadOnly"],
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 20,
}

The stand-in below uses the same shape: a permission_classes list, a has_permission() method, a page parameter and a router. It runs inside the Django test client.

Python A mini ViewSet, router and permission class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The anonymous POST was stopped by the permission class before any action ran, while the same request with the token created book 6. Everything the viewset did not implement (PUT, for example) is rejected, here after the permission check, which is also how DRF orders things: authentication and permissions run first, then the handler.

When to use DRF, and when not to

DRF shines when you have many model-backed resources and want consistent behavior: automatic validation, pagination, browsable docs and a large ecosystem (filtering with django-filter, schema generation, throttling). Its learning curve is real, though, because the same task can be done with serializers, generic views or ViewSets, and the magic can hide what is happening.

Consider alternatives when the API is small (plain JsonResponse views are fine), when you want type-driven validation and automatic OpenAPI docs (packages such as Django Ninja use Python type hints), or when the service is fully asynchronous. The ideas you have learned here carry over to all of them: resources, validation, permissions, pagination and versioning.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the two jobs of a DRF serializer?

    A serializer turns model instances into JSON-ready data (output) and validates untrusted request data into clean validated_data or errors (input).
  2. 2. What does a router do for a ViewSet?

    One ViewSet handles several URLs, so a router inspects it and registers the collection and member routes for you, for example book-list and book-detail.
  3. 3. In which order do these steps run for a DRF request?

    DRF first identifies the caller (authentication), then checks access (permissions), and only then runs the action, which uses a serializer to validate or format data.
  4. 4. Which method name validates a single field called pages in a DRF serializer?

    DRF uses validate_<field_name> for one field and validate() for rules across several fields. Django forms use clean_<field> instead.

Summary

  • DRF bundles the repetitive parts of an API: serializers, views, routers, permissions, authentication and pagination.
  • A serializer converts objects to plain data and validates untrusted input; ModelSerializer generates fields from a model.
  • Choose among APIView, generic views and ModelViewSet by how much behavior you want for free.
  • Routers turn a ViewSet into list and detail URLs; permission and authentication classes run before the action.
  • Configure defaults in the REST_FRAMEWORK setting, and pick plain views or lighter libraries for small APIs.

Next lesson: DRF Serializers in Depth.