The Ultimate Step-by-Step Guide to Mastering Django REST Framework
Django REST Framework (DRF) is arguably the single most powerful and widely adopted toolkit for building robust, scalable, and maintainable Web APIs in Python. It seamlessly integrates with the Django web framework, extending its capabilities to transform your database models into fully functional RESTful endpoints with minimal boilerplate code. Whether you are a seasoned Django developer looking to branch into API development or a newcomer eager to learn how to build a backend that can power single‑page applications, mobile apps, or third‑party integrations, understanding DRF is an essential skill. This guide is designed to take you from zero to a fully deployable API, covering every critical concept, from serializers and viewsets to authentication, permissions, filtering, and testing. Each section is written to be both instructive and immediately applicable, with real‑world examples and best practices that will save you hours of debugging. By the end, you will not only know how to use DRF but also why it works the way it does, empowering you to build custom, high‑performance APIs that adhere to industry standards.
Let’s start by setting the stage: what makes DRF different from simply using Django’s built‑in JSON response utilities? The answer lies in its comprehensive set of abstractions. Instead of manually parsing request bodies, handling authentication for every view, paginating querysets, or writing complex serialization logic, DRF gives you declarative serializers, class‑based views, viewsets, routers, and granular permission classes. All of this is built on top of Django’s model‑view‑template architecture but repurposed for a JSON‑first, API‑centric workflow. In this tutorial, we will build a complete API for a hypothetical blog platform—with models for Post, Comment, and Category—and expose endpoints that are fully browsable, authenticated, and documented. We will cover everything from the initial project setup to advanced features like nested serializers, throttling, and versioning. So, roll up your sleeves, fire up your terminal, and let’s dive into the world of Django REST Framework.
1. Project Setup and Installing DRF
Before writing a single line of API code, you need to have a working Django project and virtual environment. If you already have an existing Django project, you can skip ahead to installing DRF. For those starting from scratch, the following commands will get you a fresh, isolated environment. We are using Python 3.10+ and Django 4.2 LTS, though the steps are similar for other recent versions.
Step 1.1: Create a virtual environment and install Django
It is always recommended to use a virtual env to avoid conflicts between project dependencies.
python -m venv env
source env/bin/activate # On Windows: env\Scripts\activate
pip install django
Step 1.2: Create a Django project and an app
For this tutorial, we will name our project blogapi and create an app called blog to hold our models and API logic.
django-admin startproject blogapi
cd blogapi
python manage.py startapp blog
Step 1.3: Install Django REST Framework
With your virtual environment active and inside the project directory, install DRF:
pip install djangorestframework
Optionally, if you plan to use the browsable API with forms (highly recommended during development), also install the optional django-filter package for advanced filtering:
pip install django-filter
Step 1.4: Add DRF to INSTALLED_APPS
Open blogapi/settings.py and locate the INSTALLED_APPS list. Add 'rest_framework' at the end. If you installed django-filter, also add 'django_filters'. Your settings should now look like this:
INSTALLED_APPS = [
# Django default apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third-party apps
'rest_framework',
'django_filters', # if installed
# Local apps
'blog',
]
Now run migrations and create a superuser (for testing authentication later):
python manage.py migrate
python manage.py createsuperuser
Your environment is ready. Next, we will build our data models and serializers.
2. Defining the Data Models and Migrations
The heart of any API is the data it serves. Let’s create models for a blog. Open blog/models.py and define the following classes:
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
class Meta:
verbose_name_plural = "categories"
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='posts')
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
is_published = models.BooleanField(default=False)
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Comment by {self.author.username} on {self.post.title}"
Run the migrations:
python manage.py makemigrations
python manage.py migrate
Now that we have our data model, we need a way to convert these Python objects into JSON (serialization) and to validate incoming data. DRF provides Serializers for exactly this purpose.
3. Creating Serializers
Serializers in DRF are analogous to Django Forms. They define how model instances are transformed into JSON and how JSON (or other content types) is validated and deserialized back into Python objects. There are two main approaches: Serializer (manual fields) and ModelSerializer (automatic fields based on the model). For most cases, ModelSerializer is the better choice because it reduces boilerplate, ensures consistency with the model definition, and provides default implementations for create and update operations.
Create a new file blog/serializers.py and add:
from rest_framework import serializers
from .models import Category, Post, Comment
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ['id', 'name', 'slug']
class PostSerializer(serializers.ModelSerializer):
author = serializers.ReadOnlyField(source='author.username')
# Include related comments in the post representation (nested serializer)
comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = Post
fields = ['id', 'title', 'slug', 'author', 'category', 'content',
'created_at', 'updated_at', 'is_published', 'comments']
read_only_fields = ['created_at', 'updated_at']
class CommentSerializer(serializers.ModelSerializer):
author = serializers.ReadOnlyField(source='author.username')
class Meta:
model = Comment
fields = ['id', 'post', 'author', 'body', 'created_at']
read_only_fields = ['created_at']
Explanation: The ReadOnlyField ensures that the author field is populated automatically from the request user (we will handle that in the view) and is not expected in the request body. PrimaryKeyRelatedField for comments returns a list of comment IDs—alternatively you could use a nested serializer to include full comment objects. The read_only_fields ensure timestamps are never sent by the client.
Now that we have serializers, we can use them in views. But before jumping to views, it is important to understand the workflow:
| Serializer Method | Purpose |
|---|---|
serializer.is_valid() |
Validates the incoming data against field constraints |
serializer.validated_data |
Returns cleaned data after successful validation |
serializer.save() |
Creates or updates a model instance based on validated_data |
serializer.data |
Returns the serialized representation (dict) for the response |
4. Building Views (Function-Based and Class-Based)
DRF offers several ways to write views. The simplest is a function-based view using the @api_view decorator. More powerful and reusable are class-based views like APIView or the generic views that mixin common behavior. Finally, for a fully CRUD API, we have ViewSet coupled with Router. In this tutorial we will start with a class-based generic view for PostList and PostDetail to demonstrate control, then migrate to a ViewSet for the complete set.
Step 4.1: Using Generic Class-Based Views
Open blog/views.py and begin by importing the necessary components:
from rest_framework import generics
from .models import Post, Comment, Category
from .serializers import PostSerializer, CommentSerializer, CategorySerializer
from rest_framework.permissions import IsAuthenticatedOrReadOnly
class PostList(generics.ListCreateAPIView):
queryset = Post.objects.filter(is_published=True)
serializer_class = PostSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
# Automatically set the author to the current user
serializer.save(author=self.request.user)
class PostDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
These two views provide a full range of endpoints: GET (list), POST, GET (detail), PUT/PATCH, DELETE. The perform_create method is a DRF hook that allows us to inject the authenticated user into the author field before saving.
Step 4.2: Wiring Up URLs Manually
Create a file blog/urls.py and add paths:
from django.urls import path
from . import views
urlpatterns = [
path('posts/', views.PostList.as_view(), name='post-list'),
path('posts/<int:pk>/', views.PostDetail.as_view(), name='post-detail'),
]
Then include this in the root URL configuration (blogapi/urls.py):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('blog.urls')),
]
You can now test the API by running python manage.py runserver and visiting http://127.0.0.1:8000/api/posts/ in your browser. You should see the browsable API interface.
Step 4.3: Moving to ViewSets and Routers
For a more DRY and maintainable approach, especially when you have multiple models and standard CRUD operations, use a ModelViewSet. This combines all list, create, retrieve, update, and delete actions into a single class. Add the following to blog/views.py:
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticatedOrReadOnly
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.filter(is_published=True)
serializer_class = PostSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save(author=self.request.user)
class CommentViewSet(viewsets.ModelViewSet):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save(author=self.request.user)
Now replace the URL configuration in blog/urls.py to use a router:
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register(r'posts', views.PostViewSet, basename='post')
router.register(r'comments', views.CommentViewSet, basename='comment')
urlpatterns = router.urls
That’s it! The router automatically generates all the standard endpoints: /posts/, /posts/{pk}/, /comments/, /comments/{pk}/. It also creates a root endpoint / that lists all available API endpoints. This is a huge time‑saver.
5. Authentication and Permissions
An API without authentication is like a house with an open door. DRF provides several authentication schemes: Basic, Token, Session, JWT (via third‑party packages). For this tutorial, we will implement Token Authentication, which is ideal for mobile apps or third‑party clients. Additionally, we will refine permission classes to control read/write access at a granular level.
Step 5.1: Enabling Token Authentication
First install the token auth app:
pip install djangorestframework authtoken
Wait, actually rest_framework.authtoken is included in DRF itself. Simply add 'rest_framework.authtoken' to your INSTALLED_APPS. Run migrations to create the token model:
python manage.py migrate
Then, in settings.py, set the default authentication classes:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated', # Global default
]
}
For the browsable API, SessionAuthentication is convenient; for programmatic clients, TokenAuthentication is used. You’ll need to provide a way for users to obtain a token. Typically you create a simple view or use the built‑in obtain_auth_token view. Add this to your blog/urls.py:
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns += [
path('api-token-auth/', obtain_auth_token, name='api_token_auth'),
]
Now any user can POST their username and password to /api-token-auth/ and receive a token. That token must be included in the Authorization header of subsequent requests: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b.
Step 5.2: Custom Permissions
Often you want to allow only the author of a post to edit or delete it. While IsAuthenticatedOrReadOnly prevents anonymous edits, it does not restrict against other logged‑in users. Let’s create a custom permission in blog/permissions.py:
from rest_framework import permissions
class IsAuthorOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow authors of an object to edit it.
Assumes the model instance has an `author` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed for any request
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed to the author of the post
return obj.author == request.user
Now apply this permission to your PostViewSet:
permission_classes = [IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly]
Note: object-level permissions require that you call check_object_permissions manually if you override get_object() in a generic view. In viewsets, this is handled automatically.
6. Filtering, Ordering, and Search
Real‑world APIs need to give clients the ability to filter, sort, and search results. DRF includes a powerful filtering system, and you can integrate django-filter for even richer capabilities. We’ll add filtering to the PostViewSet.
Step 6.1: Enable Django Filter Backend
In settings.py, add the filter backend:
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': [
'django_filters.rest_framework.DjangoFilterBackend',
'rest_framework.filters.SearchFilter',
'rest_framework.filters.OrderingFilter',
],
...
}
Step 6.2: Apply Filtering to the ViewSet
Update your PostViewSet to include filterset_fields, search_fields, and ordering_fields:
from rest_framework import filters
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.filter(is_published=True)
serializer_class = PostSerializer
permission_classes = [IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly]
filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
filterset_fields = ['category', 'author', 'is_published']
search_fields = ['title', 'content']
ordering_fields = ['created_at', 'title']
ordering = ['-created_at']
def perform_create(self, serializer):
serializer.save(author=self.request.user)
Now clients can do requests like:
GET /api/posts/?category=1&author=2GET /api/posts/?search=django+restGET /api/posts/?ordering=title
For more complex filtering (e.g., date range), you can create a custom FilterSet class. This flexibility makes your API much more usable.
7. Pagination, Throttling, and Versioning
Large APIs need to protect resources from abuse and ensure smooth performance. DRF has built‑in support for pagination, throttling, and API versioning.
7.1 Pagination
In settings.py define a global pagination style:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}
You can also define custom pagination classes per view using pagination_class attribute. The response will include the total count, next/previous links, and results.
7.2 Throttling
Throttling limits the number of requests a user can make in a given time frame. It’s essential for preventing brute‑force attacks and API abuse. Add to settings:
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': '1000/day'
}
}
You can also set per‑view throttling by defining throttle_classes and throttle_scope.
7.3 API Versioning
To support backward compatibility, you can version your API via URL namespace, query parameter, or header. URL‑based versioning is the clearest.
Modify your root blogapi/urls.py to prefix versions:
urlpatterns = [
path('api/v1/', include('blog.urls')),
]
Then, in your blog/urls.py you can use the same router. If you later need to break changes, you create v2 urls.
8. Testing Your API
DRF provides excellent testing utilities, combining Django’s TestCase with an API request factory and client. We will write tests for the Post endpoints. Create a file blog/tests.py:
from django.test import TestCase
from rest_framework.test import APIClient
from rest_framework import status
from django.contrib.auth.models import User
from .models import Post, Category
class PostAPITestCase(TestCase):
def setUp(self):
self.client = APIClient()
self.user = User.objects.create_user(username='testuser', password='testpass')
self.category = Category.objects.create(name='Tech', slug='tech')
self.post_data = {
'title': 'Test Post',
'slug': 'test-post',
'content': 'Testing content',
'category': self.category.id,
}
def test_create_post_authenticated(self):
self.client.force_authenticate(user=self.user)
response = self.client.post('/api/posts/', self.post_data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Post.objects.count(), 1)
self.assertEqual(Post.objects.get().author, self.user)
def test_create_post_unauthenticated(self):
response = self.client.post('/api/posts/', self.post_data, format='json')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_get_posts_list(self):
Post.objects.create(title='Existing', slug='existing', content='...', author=self.user, category=self.category, is_published=True)
response = self.client.get('/api/posts/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data['results']), 1)
Run tests with python manage.py test. Always test both positive (authenticated) and negative (unauthorized) scenarios, as well as edge cases like missing fields or invalid data.
Tips and Best Practices
Tip 1: Use drf-yasg or drf-spectacular for Auto-Generated API Documentation
One of the strongest selling points of DRF is the browsable API, but for real consumers, you need proper documentation. Packages like drf-spectacular (OpenAPI 3.0 compliant) automatically generate interactive Swagger UI docs from your views and serializers. It reduces friction between frontend and backend teams.
Tip 2: Keep Your Serializers Clean and Aligned with Business Logic
Avoid putting too much logic in the view; instead, use custom serializer methods (validate_, update, create) and nested serializers to handle complex payloads. For example, if a post needs to create a category on the fly, override create in the serializer.
Tip 3: Always Set Explicit related_name on ForeignKeys
It makes serialization and queryset filtering far more readable. As we did above with posts, comments, etc. This prevents clashes and improves code clarity.
Tip 4: Use reverse for URL Resolution Inside Serializers
If you need to include a link to the resource detail in a list response, use serializers.HyperlinkedModelSerializer instead of the default primary key. It generates fully qualified URLs and makes your API more RESTful.
Frequently Asked Questions
Q1: What is the difference between APIView and ViewSet?
APIView is the base class for all DRF views. It gives you full control over how to handle each HTTP method. A ViewSet is a higher‑level abstraction that groups all related actions (list, create, retrieve, update, partial_update, destroy) into one class. When combined with a Router, it automatically generates the URL patterns. For most CRUD scenarios, ModelViewSet is the easiest and most maintainable choice.
Q2: How do I handle nested relationships (e.g., create a comment under a post) in DRF?
You have two main approaches. The first is to use a nested router (package drf-extensions) or write a dedicated view that manually filters the queryset by the parent slug or id. The second is to include the parent identifier (like post_id) in the serializer and rely on the user to include it in the request. For more complex nested writes, you can override create in the serializer to instantiate the related object. Always validate that the parent exists.
Q3: Can I use Django REST Framework with GraphQL instead of REST?
DRF is specifically designed for REST. For GraphQL, you would use Graphene-Django or Strawberry. However, you can integrate both in the same project; DRF can handle REST endpoints for certain use cases while GraphQL handles complex queries.
Q4: How do I limit which fields are exposed based on the user’s role?
You can dynamically modify the serializer’s fields in the __init__ method based on the request context. For example, you can remove the content field for unauthenticated users. Alternatively, create multiple serializers and choose the appropriate one in the view via get_serializer_class(). DRF’s flexibility allows you to tailor the API response to the user’s permissions.
Q5: Why am I getting a 405 Method Not Allowed error for a ViewSet?
This usually happens when the URL pattern does not map to the intended action. For example, if you define a @action(detail=True) on a ViewSet but forget to set the correct HTTP method in the decorator (e.g., methods=['post']). Also ensure the router is registered with the correct basename and that the queryset is not filtered to something that cannot be written to (like a read‑only property).
Q6: How do I prevent an anonymous user from seeing any data at all?
Set the default permission class to IsAuthenticated globally in settings.py. Then override specific views with AllowAny if needed (e.g., the login endpoint). This ensures all endpoints require authentication unless explicitly exempted.
Conclusion
Django REST Framework is a mature, battle‑tested library that empowers developers to build APIs quickly without sacrificing quality or security. In this tutorial, we have covered every essential aspect: from project setup, model definition, serialization, various view patterns, authentication, permissions, filtering, pagination, throttling, versioning, and testing. We also explored best practices like using routers, custom permissions, and auto‑generated documentation.
By following the step‑by‑step guide, you have built a fully functional RESTful API for a blog platform that is ready for production after adding HTTPS, CORS headers (django‑cors‑headers), and perhaps a database backend like PostgreSQL. The true power of DRF lies in its extensibility: you can easily add HATEOAS links, content negotiation, custom exception handlers, and integration with caching. The knowledge you gained here forms a solid foundation that can be applied to any domain—e‑commerce, social media, IoT, or SaaS. Now go ahead and build your next great API, and remember to always think about your clients: they will appreciate well‑structured, documented, and consistent endpoints. Happy coding!