Django REST Framework
The previous lesson built a JSON API by hand. That works, but every endpoint repeats the same chores: convert models to dictionaries, parse and validate input, return the right status codes, handle authentication and pagination. Django REST Framework (DRF) is the de-facto standard third-party package that does these chores for you. It's used by a huge share of Django projects that expose an API.
Note: DRF is a separate package and is not installed in this site's playground, so the code in this lesson is shown as regular (non-runnable) code with the output you'd see in a real project.
| Concept | Plain Django | DRF |
|---|---|---|
| Model ↔ JSON | hand-written to_dict() |
Serializer / ModelSerializer |
| Input validation | Django forms | serializers (same ideas) |
| Views | View / function views |
APIView, generic views, ViewSet |
| URLs | one path() per endpoint |
Router generates them |
| Auth | sessions | sessions, tokens, JWT (via add-ons), permissions classes |
| Docs | none | browsable API in the browser |
Installing
pip install djangorestframeworkSuccessfully installed djangorestframework-3.16.1
# settings.py
INSTALLED_APPS = [
# ...
"rest_framework",
"books",
]
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticatedOrReadOnly"],
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 20,
}Serializers
A serializer converts model instances to Python primitives (and then JSON), and validates incoming data — think of it as a ModelForm for APIs:
# books/serializers.py
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ["id", "title", "author", "year"]
read_only_fields = ["id"]
def validate_year(self, value): # like clean_year() on a form
if value > 2026:
raise serializers.ValidationError("Year can't be in the future.")
return valueUsing it in python manage.py shell:
>>> book = Book.objects.create(title="Kindred", author="Octavia E. Butler", year=1979)
>>> BookSerializer(book).data
{'id': 1, 'title': 'Kindred', 'author': 'Octavia E. Butler', 'year': 1979}
>>> s = BookSerializer(data={"title": "Future book", "author": "X", "year": 2999})
>>> s.is_valid()
False
>>> s.errors
{'year': [ErrorDetail(string="Year can't be in the future.", code='invalid')]}is_valid(), errors, validated_data and save() mirror the form API you already know.
ViewSets and routers
A ViewSet bundles the list, create, retrieve, update and delete actions for one resource. A router generates the URL patterns for it:
# books/views.py
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.order_by("id")
serializer_class = BookSerializer# mysite/urls.py
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from books.views import BookViewSet
router = DefaultRouter()
router.register("books", BookViewSet)
urlpatterns = [
path("api/", include(router.urls)),
]Those few lines create a complete REST API:
| Method & URL | Action |
|---|---|
GET /api/books/ |
list (paginated) |
POST /api/books/ |
create |
GET /api/books/1/ |
retrieve |
PUT / PATCH /api/books/1/ |
update |
DELETE /api/books/1/ |
delete |
Calling the API
With runserver running, you can call the API from the command line. Here with curl (the -u option sends HTTP Basic credentials, enabled by default for authenticated writes):
curl -s http://127.0.0.1:8000/api/books/
curl -s -X POST http://127.0.0.1:8000/api/books/ -u admin:secret \
-H "Content-Type: application/json" \
-d '{"title": "Beloved", "author": "Toni Morrison", "year": 1987}'
curl -s -X POST http://127.0.0.1:8000/api/books/ \
-H "Content-Type: application/json" -d '{"title": "Anonymous"}'{"count":1,"next":null,"previous":null,"results":[{"id":1,"title":"Kindred","author":"Octavia E. Butler","year":1979}]}
{"id":2,"title":"Beloved","author":"Toni Morrison","year":1987}
{"detail":"Authentication credentials were not provided."}
The anonymous POST was rejected by IsAuthenticatedOrReadOnly (status 403). Open http://127.0.0.1:8000/api/books/ in a browser and DRF shows its browsable API — an HTML page where you can read and submit data, generated automatically.
Function-style API views
Not everything is a CRUD resource. The @api_view decorator turns a function into an API view with content negotiation and DRF's Response:
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from django.db.models import Count
@api_view(["GET"])
@permission_classes([AllowAny])
def stats(request):
by_decade = (Book.objects.values("year")
.annotate(n=Count("id")).order_by("year"))
return Response({"total": Book.objects.count(), "by_year": list(by_decade)})Testing DRF endpoints
DRF ships APIClient and APITestCase, which work like Django's test client with JSON helpers:
from rest_framework.test import APITestCase
from django.contrib.auth.models import User
class BookApiTests(APITestCase):
def test_create_requires_login(self):
r = self.client.post("/api/books/", {"title": "X", "author": "Y", "year": 2000}, format="json")
self.assertEqual(r.status_code, 403)
def test_create(self):
self.client.force_authenticate(User.objects.create_user("u"))
r = self.client.post("/api/books/", {"title": "X", "author": "Y", "year": 2000}, format="json")
self.assertEqual(r.status_code, 201)
self.assertEqual(r.data["title"], "X")Under the hood: it's still Django
Everything DRF does rests on what you've learned: a serializer is a richer form, a ViewSet is a class-based view, a router writes path() entries, and permissions are checks in dispatch(). As a reminder, here's the core of ModelSerializer's job done with plain Django — runnable:
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.forms.models import model_to_dict
from django.core.serializers import serialize
class Book(models.Model):
title = models.CharField(max_length=100)
year = models.IntegerField()
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(Book)
Book.objects.create(title="Kindred", year=1979)
print(model_to_dict(Book.objects.get(pk=1)))
print(serialize("json", Book.objects.all())){'id': 1, 'title': 'Kindred', 'year': 1979}
[{"model": "demo.book", "pk": 1, "fields": {"title": "Kindred", "year": 1979}}]
Django's built-in serialize() is designed for fixtures (data dumps), not public APIs — which is exactly the gap DRF fills.
Tip: Other popular API options are django-ninja (type-hint based, similar to FastAPI) and plain
JsonResponseviews for tiny APIs.
Test yourself
In DRF, what plays the role that ModelForm plays for HTML forms?
- ViewSet
- Router
- ModelSerializer
- APIView
What does router.register("books", BookViewSet) do?
- Creates the Book table
- Generates URL patterns for the list and detail endpoints
- Registers the model with the admin
- Adds a permission
With IsAuthenticatedOrReadOnly, what can an anonymous client do?
- Nothing
- Only GET (read) requests
- Everything
- Only POST