Django REST Framework Tutorial
Learn Django REST Framework step by step: 39 lessons in 9 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is Django REST Framework? Learn what Django REST Framework (DRF) is, which problems it solves for web APIs, how a request flows through it, and run a real DRF endpoint in your browser.
- Your First API View Build list, create, detail, update and delete endpoints with DRF's @api_view decorator, a model and a serializer, and test each one with APIClient.
- Request, Response and Status Codes Understand DRF's Request and Response objects: request.data, query_params, user, headers, status codes and error responses, with runnable examples.
- Parsers, Renderers and Content Negotiation Learn how DRF picks parsers for request bodies and renderers for responses, how the Accept header and ?format= work, and how to enable the browsable API.
- Project Setup and the REST_FRAMEWORK Settings Set up a Django REST Framework project, add rest_framework to INSTALLED_APPS, and learn the REST_FRAMEWORK settings dictionary that controls every view's defaults.
- Exception Handling and Error Responses Raise DRF exceptions such as NotFound and ValidationError, define your own APIException classes and write a custom exception handler for consistent error JSON.
Serializers
- Serializer Basics Learn the DRF Serializer class: declared fields, converting objects to JSON-ready data, validating input, many=True, and writing create() and update().
- Serializer Fields Tour DRF serializer fields: CharField, IntegerField, ChoiceField, DateField, ListField and more, plus options like required, default, read_only, source and validators.
- ModelSerializer: Serializers Built from Models Use DRF's ModelSerializer to generate fields, validators, create() and update() from a Django model, then tune it with Meta options and extra_kwargs.
- Serializer Validation Validate API input in DRF with field options, reusable validators, validate_<field> methods, object-level validate() and UniqueTogetherValidator, with examples.
- Nested Serializers and Writable Nesting Embed one serializer inside another in Django REST Framework, serialize related objects and lists, and write nested data by overriding create() and update().
- Relational Fields: Keys, Slugs and Hyperlinks Represent relationships in DRF with PrimaryKeyRelatedField, SlugRelatedField, StringRelatedField and HyperlinkedRelatedField, including many-to-many and write behavior.
Views and ViewSets
- Class-Based Views with APIView Build DRF endpoints with the APIView class: one method per HTTP verb, get_object helpers, policy attributes, and when to prefer it over generic views.
- Generic Views and Mixins Cut DRF boilerplate with GenericAPIView, ListCreateAPIView, RetrieveUpdateDestroyAPIView and mixins. Learn queryset, serializer_class, get_queryset and perform_create.
- ViewSets: ModelViewSet and ReadOnlyModelViewSet Group list, create, retrieve, update and delete into one DRF ViewSet class. Learn ModelViewSet, ReadOnlyModelViewSet, GenericViewSet and how actions map to URLs.
- Custom Actions on ViewSets Add endpoints beyond CRUD with DRF's @action decorator: detail and list actions, url_path, per-action permissions and serializers, with runnable examples.
Routers and URLs
- Routers: Automatic URL Configuration Generate URLs for viewsets automatically with DRF's SimpleRouter and DefaultRouter. Learn register(), basename, route names, the API root view and trailing slashes.
- URL Patterns, Format Suffixes and Namespaces Write DRF URL patterns by hand, add format suffixes like .json, use reverse() and namespaces for stable links, and mix routers with ordinary paths in one project.
- Nested and Related Routes Design nested URLs like /authors/1/books/ in Django REST Framework: filter by the parent, create children with the parent set, return 404 for missing parents, and know the alternatives.
Authentication and Permissions
- Authentication Schemes in DRF Learn how Django REST Framework identifies the caller: request.user and request.auth, Basic and Session authentication, CSRF rules, 401 versus 403, and a custom API-key scheme.
- Token Authentication in DRF Add token authentication to a Django REST Framework API: the authtoken app, obtain_auth_token, a custom login and logout, automatic tokens with signals, and expiring tokens.
- JWT Authentication with Simple JWT Secure a Django REST Framework API with JSON Web Tokens using djangorestframework-simplejwt: access and refresh tokens, custom claims, expiry, rotation and blacklisting.
- DRF Permission Classes Control access in Django REST Framework with permission classes: AllowAny, IsAuthenticated, IsAdminUser, combining with and/or/not, per-action rules and DjangoModelPermissions.
- Custom and Object-Level Permissions in DRF Write your own Django REST Framework permission classes: has_permission versus has_object_permission, owner checks, scoped querysets, group roles, IP allow lists and custom error messages.
Filtering, Pagination and Throttling
- Filtering DRF Querysets with django-filter Filter Django REST Framework list endpoints by query string with django-filter: filterset_fields, lookup dictionaries, custom FilterSet classes, range and method filters and error handling.
- Search and Ordering in DRF Add free-text search and client-controlled sorting to Django REST Framework endpoints with SearchFilter and OrderingFilter, search prefixes, safe ordering fields and a custom filter backend.
- Pagination in Django REST Framework Paginate Django REST Framework list endpoints with PageNumberPagination, LimitOffsetPagination and CursorPagination, plus custom page sizes, response shapes and when to choose which style.
- Throttling and Rate Limits in DRF Protect a Django REST Framework API from abuse with throttling: AnonRateThrottle, UserRateThrottle, ScopedRateThrottle, custom throttle classes, 429 responses, Retry-After and cache backends.
Versioning and Documentation
- API Versioning in Django REST Framework Version a Django REST Framework API without breaking clients: URLPathVersioning, AcceptHeaderVersioning, query and hostname schemes, request.version, per-version serializers and deprecation.
- OpenAPI Schema Generation for DRF with drf-spectacular Generate an OpenAPI 3 schema for a Django REST Framework API with drf-spectacular: settings, extend_schema, parameters, examples, Swagger UI, Redoc and keeping the schema accurate in CI.
- The Browsable API, OPTIONS Metadata and Self-Documenting Views Use and customize the Django REST Framework browsable API: HTML rendering, OPTIONS metadata, view names and descriptions from docstrings, custom metadata and turning the HTML renderer off in production.
Testing and Deployment
- Testing DRF APIs with APIClient and APITestCase Write reliable tests for Django REST Framework APIs: APITestCase, APIClient, force_authenticate, APIRequestFactory, status and payload assertions, query counts and a testing checklist.
- Testing Authentication, Permissions and Throttling in DRF Test Django REST Framework security rules: a permission matrix with subTest, token and session login flows, CSRF checks, object-level permissions and throttle limits with a controlled clock.
- Query Optimization for DRF APIs Make Django REST Framework endpoints fast: find N+1 queries, use select_related, prefetch_related, annotate, only and defer, avoid method-field traps, and lock query counts in with tests.
- Production Settings and Deploying a DRF API Prepare a Django REST Framework API for production: deployment checks, HTTPS settings, secrets, CORS, JSON-only renderers, gunicorn and nginx, static files, logging, health checks and a release checklist.
Projects and Practice
- Project: Build a Bookstore API with Django REST Framework Build a complete Django REST Framework bookstore API: models, serializers, viewsets, filtering, search, pagination, staff-only writes, reviews with ratings, query counts and tests.
- Project: A Task Tracker API with Token Authentication Build a multi-user task tracker with Django REST Framework: sign-up and token login, per-user tasks, object permissions, custom actions for completing and summarizing, filters and tests.
- Project: A Blog API with JWT, Comments and Moderation Build a blog API with Django REST Framework: JWT login, draft and published posts, author-only editing, comments that need moderator approval, throttled posting and a tested permission model.
- Practice: DRF Exercises, Pitfalls and Interview Questions Practice Django REST Framework with hands-on exercises that check themselves, a list of the most common mistakes, capstone ideas and interview questions with short, accurate answers.