APIs with Django REST framework
Django builds websites; Django REST framework (DRF) builds APIs on top of Django. It adds serializers (convert models to and from JSON, with validation), API views and viewsets, routers that generate URLs, plus authentication, permissions, pagination, filtering and a browsable API. It's used by Mozilla, Red Hat, Heroku and thousands of companies.
pip install djangorestframework
# settings.py: INSTALLED_APPS += ["rest_framework"]Serializers
A serializer is to an API what a form is to a web page: it turns model instances into JSON-friendly data, and validates incoming data:
Note that price comes out as the string "8.99": DRF serialises decimals as strings so no precision is lost (configurable with COERCE_DECIMAL_TO_STRING).
ViewSets and routers
A ModelViewSet provides list, create, retrieve, update, partial update and destroy in one class, and a router creates all the URLs:
The router generated:
| URL | Methods | ViewSet action |
|---|---|---|
/products/ |
GET, POST | list, create |
/products/{id}/ |
GET, PUT, PATCH, DELETE | retrieve, update, partial_update, destroy |
/products/{id}/restock/ |
POST | the custom restock action |
Authentication, permissions and pagination
DRF's behaviour is configured per view or globally in settings.py:
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.SessionAuthentication", # browser sessions
"rest_framework.authentication.TokenAuthentication", # "Authorization: Token …"
],
"DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 20,
"DEFAULT_THROTTLE_RATES": {"anon": "100/day", "user": "1000/day"},
}Here's per-view configuration with a custom object-level permission (only the owner may edit a note):
Anonymous users could read but not write (403), Rahul couldn't edit Asha's note (403), and the owner was taken from the authenticated user, never from the request body.
The wider DRF ecosystem
- drf-spectacular: generates an OpenAPI schema and Swagger UI from your viewsets.
- django-filter: declarative filtering (
?category=kitchen&price__lt=20). - SimpleJWT: JWT authentication.
- django-cors-headers: CORS for separate frontends.
- Django Ninja: an alternative to DRF with a FastAPI-style, type-hint-driven API for Django.
Practice
- Add
searchsupport to the product viewset:?search=mugfilters names withicontains. - Make products readable by anyone but writable only by staff users (
IsAdminUserfor unsafe methods). - Add a nested serializer so each note shows
{"owner": {"id": 1, "username": "asha"}}.
1.What role does a DRF serializer play?
2.What does a ModelViewSet with a router give you?
3.Why set the note's owner in perform_create instead of accepting it in the request?