Lesson 46 of 59Other frameworks
Django REST Framework
Build JSON APIs on Django with serializers, APIView and ViewSets, routers, auth and permissions, pagination and filtering, and compare it with FastAPI.
Django was built for server-rendered HTML. When a team needs a JSON API for a mobile app or a React frontend, they almost always add Django REST Framework (DRF). It sits on top of Django's models, auth and admin and adds the API layer: turning model instances into JSON, validating input, auth schemes, permissions, pagination and a browsable API you can click through. If you have built the FastAPI todo API in this course, every idea here will feel familiar. The names and the amount of magic are what change.
Install and wire it up
uv add djangorestframeworkINSTALLED_APPS = [
# ... Django's own apps ...
"rest_framework",
"blog",
]
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,
}That one REST_FRAMEWORK dict sets defaults for every endpoint. Individual views can override any of them. Token auth also needs "rest_framework.authtoken" in INSTALLED_APPS and a migrate, because tokens are stored in a table.
Serializers
A serializer does two jobs that FastAPI splits between Pydantic models and your route code. Going out, it turns model instances into plain data that becomes JSON. Coming in, it validates request data and can create or update a model instance.
A ModelSerializer reads the fields from your Django model, so you do not repeat them:
from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
author = serializers.ReadOnlyField(source="author.username")
class Meta:
model = Post
fields = ["id", "title", "slug", "body", "published", "author", "created_at"]
read_only_fields = ["id", "created_at"]
def validate_title(self, value: str) -> str:
if value.strip().lower() == "untitled":
raise serializers.ValidationError("Pick a real title.")
return valueUsing it by hand looks like this:
# Out: instance to data
PostSerializer(post).data # {"id": 1, "title": "Hello", ...}
PostSerializer(posts, many=True).data # a list
# In: data to validated instance
s = PostSerializer(data=request.data)
s.is_valid(raise_exception=True) # 400 with field errors if invalid
post = s.save(author=request.user) # calls create() and returns the instancevalidate_<field> methods check one field, and a validate(self, attrs) method checks several together. Always list fields explicitly. fields = "__all__" is convenient but will quietly expose any column you add later, such as an internal note or a password hash.
Match the DRF piece to its closest FastAPI or Pydantic equivalent.
APIView: explicit handlers
The lowest common level is APIView. You write a method per HTTP verb, much like FastAPI route functions grouped in a class.
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Post
from .serializers import PostSerializer
class PostList(APIView):
def get(self, request):
posts = Post.objects.filter(published=True).select_related("author")
return Response(PostSerializer(posts, many=True).data)
def post(self, request):
serializer = PostSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save(author=request.user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
class PostDetail(APIView):
def get(self, request, pk: int):
post = get_object_or_404(Post, pk=pk)
return Response(PostSerializer(post).data)request.data holds the parsed body (JSON or form data), request.query_params the query string, and Response renders to JSON. Hook it up with path("posts/", PostList.as_view()). The default permission classes from settings already apply to these views.
ViewSets and routers
Most endpoints are the same five operations on a model: list, create, retrieve, update, delete. A ModelViewSet gives you all of them from two attributes, and a router generates the URLs.
from rest_framework import permissions, viewsets
from .models import Post
from .permissions import IsAuthorOrReadOnly
from .serializers import PostSerializer
class PostViewSet(viewsets.ModelViewSet):
serializer_class = PostSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly]
def get_queryset(self):
return Post.objects.filter(published=True).select_related("author")
def perform_create(self, serializer):
serializer.save(author=self.request.user)from rest_framework.routers import DefaultRouter
from .views import PostViewSet
router = DefaultRouter()
router.register("posts", PostViewSet, basename="post")
urlpatterns = router.urlsThat registration produces:
| Method and path | ViewSet action |
|---|---|
GET /posts/ | list |
POST /posts/ | create |
GET /posts/{pk}/ | retrieve |
PUT /posts/{pk}/ | update |
PATCH /posts/{pk}/ | partial_update |
DELETE /posts/{pk}/ | destroy |
Need fewer operations? Use ReadOnlyModelViewSet or combine mixins. Need an extra endpoint like POST /posts/{pk}/publish/? Add a method with the @action(detail=True, methods=["post"]) decorator and the router picks it up.
Overriding get_queryset instead of setting a class-level queryset matters: it runs per request, so you can filter by self.request.user and nobody sees other users' rows.
ModelViewSet as router.register("posts", PostViewSet). Which request runs its partial_update action?The router maps POST on the list URL to the create action.
Authentication and permissions
DRF separates two questions. Authentication asks who you are: each class in DEFAULT_AUTHENTICATION_CLASSES tries to identify the user from the request (a session cookie, a Token header, or a JWT through a package such as djangorestframework-simplejwt). Permissions ask whether you may do this: each class in permission_classes must allow the request.
Built-ins cover common cases: AllowAny, IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly. For "only the author can edit", write an object permission:
from rest_framework import permissions
class IsAuthorOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj) -> bool:
if request.method in permissions.SAFE_METHODS:
return True
return obj.author == request.userhas_object_permission runs when the view fetches a single object with get_object(), which the generic views and viewsets do for retrieve, update and destroy. If you write your own APIView and fetch with get_object_or_404, object permissions are not checked unless you call self.check_object_permissions(request, obj) yourself. That gap is a common source of broken access control.
IsAuthenticatedOrReadOnly. What happens?Pagination and filtering
With DEFAULT_PAGINATION_CLASS set, list endpoints return a wrapped page:
{
"count": 42,
"next": "https://api.example.com/posts/?page=2",
"previous": null,
"results": [{ "id": 1, "title": "Hello" }]
}PageNumberPagination uses ?page=, LimitOffsetPagination uses ?limit=&offset=, and CursorPagination uses an opaque cursor that stays stable while rows are being inserted, which suits large or fast-changing feeds.
For filtering, the simplest approach is in get_queryset using self.request.query_params. For declarative filters, most teams add django-filter:
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
class PostViewSet(viewsets.ModelViewSet):
# ...
filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
filterset_fields = ["published", "author"]
search_fields = ["title", "body"]
ordering_fields = ["created_at", "title"]Now ?published=true&search=django&ordering=-created_at works with no extra code. On large tables, make sure the columns you filter and order by are indexed.
PAGE_SIZE is 20 and the table has 42 posts. How many items are in results on GET /posts/?page=3?
GET /posts/?page=3
Throttling
DRF also has throttling built in, a simple form of rate limiting. Set DEFAULT_THROTTLE_CLASSES to AnonRateThrottle and UserRateThrottle, and DEFAULT_THROTTLE_RATES to values like "anon": "100/hour". Clients over the limit get a 429 Too Many Requests. The counts live in Django's cache, so with several server processes you need a shared cache such as Redis, or each process counts separately and the limit is effectively multiplied.
Related data in responses
Clients often want related data inline, such as a post with its author and tags. You have three common options, each with a cost.
- Primary keys: the default for a
ForeignKeyin aModelSerializer. The response has"author": 3. Cheap, but the client needs a second request. - A single field from the relation:
serializers.ReadOnlyField(source="author.username"), as in the example above. Good for one or two values. - A nested serializer:
author = UserSerializer(read_only=True)puts the whole user object inside each post.
Nested serializers are read only by default. Writing nested data (creating a post and its tags in one request) needs you to override create() and update() yourself, and many teams avoid it by accepting ids on input and returning nested objects on output, often with two serializers. That is the same input model versus output model split you used in FastAPI.
Testing a DRF API
DRF ships APITestCase and APIClient, which extend Django's test tools with JSON helpers and a way to log in without a real token flow:
from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.test import APITestCase
class PostApiTests(APITestCase):
def setUp(self):
self.user = get_user_model().objects.create_user("ada", password="pw")
def test_anonymous_cannot_create(self):
response = self.client.post("/posts/", {"title": "Hi", "slug": "hi", "body": "x"}, format="json")
self.assertIn(response.status_code, {status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN})
def test_author_can_create(self):
self.client.force_authenticate(user=self.user)
response = self.client.post("/posts/", {"title": "Hi", "slug": "hi", "body": "x"}, format="json")
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data["author"], "ada")force_authenticate plays the role of dependency_overrides for the current user in FastAPI tests. Many teams run these with pytest and the pytest-django plugin instead of Django's runner; the client works the same way.
DRF compared with FastAPI
| Django REST Framework | FastAPI | |
|---|---|---|
| Validation | Serializers | Pydantic models from type hints |
| Routing | Routers generate CRUD URLs | One decorator per route |
| Data layer | Django ORM, migrations, admin built in | Your choice, usually SQLAlchemy and Alembic |
| Auth | Session, token, permissions classes built in | You compose it with dependencies |
| Docs | Browsable API; OpenAPI via a package like drf-spectacular | OpenAPI and /docs built in |
| Async | Mostly synchronous | Async first |
| Code volume for CRUD | Very low with ViewSets | More explicit, more lines |
DRF wins when you already have Django or want its admin and auth, and when the API is mostly CRUD over models. FastAPI wins when you want typed request and response models everywhere, built-in docs, async I/O and explicit code over class magic.
- serializer
- A DRF class that turns model instances into data and validates incoming data into instances.
- APIView
- A class-based view with one method per HTTP verb, plus DRF auth, permissions and parsing.
- ViewSet
- A class that groups actions like list and retrieve; a router maps them to URLs.
- router
- Generates URL patterns for a ViewSet's actions, such as
/posts/and/posts/{pk}/. - permission class
- Decides whether a request, or an action on one object, is allowed.
- pagination class
- Splits list responses into pages, by page number, limit and offset, or cursor.