How to Build REST APIs with Django Rest Framework: A Practical Guide

Building APIs is no longer optional for web developers — it is the foundation of every modern application. Whether you are creating a mobile app backend, a single-page application, or connecting microservices, REST APIs are how your frontend talks to your backend. Django Rest Framework (DRF) makes building robust, production-ready APIs surprisingly straightforward, even for developers new to backend work. This Django REST API tutorial walks you through the entire process of building a complete API from scratch, with working code examples, authentication setup, and best practices that will serve you in real projects — whether you are building for a Nepali startup or freelancing for international clients.
What Is Django Rest Framework and Why Should You Use It?
Django Rest Framework is a powerful toolkit built on top of Django that simplifies building Web APIs. It provides serialization, authentication, viewsets, routers, and a browsable API interface out of the box, saving you weeks of development time.
DRF takes Django's already productive "batteries-included" philosophy and extends it specifically for API development. Instead of writing raw JSON responses and manually handling request parsing, DRF gives you:
- Serializers: Automatically convert Django models to JSON and validate incoming data
- ViewSets and Routers: Generate entire CRUD API endpoints from a single class
- Authentication: Built-in support for token auth, session auth, JWT, and OAuth
- Permissions: Granular access control at the view or object level
- Browsable API: A web interface to test your API directly in the browser
- Pagination: Automatic response pagination for large datasets
- Throttling: Rate limiting to protect your API from abuse
- Filtering and Search: Query parameter-based filtering with minimal code
Why DRF over alternatives:
| Feature | Django Rest Framework | Flask + Marshmallow | FastAPI | Express.js |
|---|---|---|---|---|
| Learning Curve | Moderate | Easy | Easy | Easy |
| Built-in Admin | Yes (Django Admin) | No | No | No |
| ORM | Django ORM (powerful) | SQLAlchemy (flexible) | SQLAlchemy | None built-in |
| Authentication | Built-in (multiple) | Manual setup | Manual setup | Manual setup |
| Browsable API | Yes | No | Yes (Swagger) | No |
| Community Size | Very Large | Large | Growing | Very Large |
| Best For | Full-featured APIs | Simple APIs | High-performance APIs | JavaScript teams |
For most web applications, especially those that need an admin panel, user authentication, and a relational database, DRF is the most productive choice. You can build in hours what would take days with other frameworks.
How Do You Set Up a Django Rest Framework Project from Scratch?
Set up a DRF project by creating a virtual environment, installing Django and djangorestframework, creating a new Django project and app, then adding rest_framework to your INSTALLED_APPS in settings.py.
Here is the complete setup process:
# Step 1: Create and activate a virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Step 2: Install Django and DRF
pip install django djangorestframework
# Step 3: Create a new Django project
django-admin startproject myapi .
# Step 4: Create an app for your API
python manage.py startapp products
# Step 5: Run initial migrations
python manage.py migrate
# Step 6: Create a superuser for the admin panel
python manage.py createsuperuser
Now configure your settings.py:
# myapi/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third-party apps
'rest_framework',
# Your apps
'products',
]
# DRF Configuration
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
],
}
Next, create your model:
# products/models.py
from django.db import models
class Product(models.Model):
"""
Product model for our e-commerce API.
Each product has a name, description, price, and metadata.
"""
name = models.CharField(max_length=200)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
category = models.CharField(max_length=100)
in_stock = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return self.name
# Run migrations to create the database table
python manage.py makemigrations products
python manage.py migrate
How Do Serializers Work in Django Rest Framework?
Serializers in DRF convert complex Django model instances into Python dictionaries (which are then rendered as JSON), and also handle deserialization — converting incoming JSON data back into validated model instances for saving to the database.
Think of serializers as the translator between your database and your API. They handle:
- Serialization: Model instance to JSON (for API responses)
- Deserialization: JSON to validated data (for creating/updating records)
- Validation: Ensuring incoming data meets your requirements
# products/serializers.py
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
"""
Serializer for the Product model.
ModelSerializer automatically generates fields based on the model.
"""
# Custom field: calculate discount price
discount_price = serializers.SerializerMethodField()
class Meta:
model = Product
fields = [
'id', 'name', 'description', 'price',
'category', 'in_stock', 'discount_price',
'created_at', 'updated_at'
]
read_only_fields = ['id', 'created_at', 'updated_at']
def get_discount_price(self, obj):
"""Calculate a 10% discount price."""
return float(obj.price) * 0.9
def validate_price(self, value):
"""Ensure price is positive."""
if value <= 0:
raise serializers.ValidationError(
"Price must be greater than zero."
)
return value
def validate(self, data):
"""
Object-level validation.
Check that name and description are not the same.
"""
if data.get('name') == data.get('description'):
raise serializers.ValidationError(
"Name and description should be different."
)
return data
Types of serializers in DRF:
| Serializer Type | Use Case | Complexity |
|---|---|---|
Serializer |
Full manual control over fields and validation | High |
ModelSerializer |
Auto-generates fields from a Django model | Low |
HyperlinkedModelSerializer |
Like ModelSerializer but uses URLs instead of IDs | Low |
ListSerializer |
Handle lists of objects | Moderate |
For most projects, ModelSerializer is what you want. It automatically creates serializer fields for every model field, includes default create() and update() implementations, and generates validators based on your model constraints.
How Do You Create API Views and URL Routing in DRF?
DRF offers three levels of abstraction for API views: function-based views with @api_view, class-based APIView for more control, and ViewSets with routers for automatic URL generation — each suited to different complexity levels.
Let us build all three approaches so you understand when to use each:
Approach 1: Function-Based Views (Simple)
# products/views.py
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from .models import Product
from .serializers import ProductSerializer
@api_view(['GET', 'POST'])
def product_list(request):
"""
GET: Return all products
POST: Create a new product
"""
if request.method == 'GET':
products = Product.objects.all()
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = ProductSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(
serializer.data,
status=status.HTTP_201_CREATED
)
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST
)
@api_view(['GET', 'PUT', 'DELETE'])
def product_detail(request, pk):
"""
GET: Return a single product
PUT: Update a product
DELETE: Delete a product
"""
try:
product = Product.objects.get(pk=pk)
except Product.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = ProductSerializer(product)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = ProductSerializer(product, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST
)
elif request.method == 'DELETE':
product.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
Approach 2: ViewSets with Routers (Recommended)
# products/views.py
from rest_framework import viewsets, filters
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from django_filters.rest_framework import DjangoFilterBackend
from .models import Product
from .serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
"""
A ViewSet that provides complete CRUD operations for Products.
list: GET /api/products/
create: POST /api/products/
read: GET /api/products/{id}/
update: PUT /api/products/{id}/
partial: PATCH /api/products/{id}/
delete: DELETE /api/products/{id}/
"""
queryset = Product.objects.all()
serializer_class = ProductSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
filter_backends = [
DjangoFilterBackend,
filters.SearchFilter,
filters.OrderingFilter,
]
filterset_fields = ['category', 'in_stock']
search_fields = ['name', 'description']
ordering_fields = ['price', 'created_at']
# products/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views
# The router automatically generates URL patterns for the ViewSet
router = DefaultRouter()
router.register(r'products', views.ProductViewSet)
urlpatterns = [
path('', include(router.urls)),
]
# myapi/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('products.urls')),
# DRF's browsable API login
path('api-auth/', include('rest_framework.urls')),
]
With just these few lines, the ViewSet and Router combination gives you six fully functional API endpoints with filtering, search, ordering, and pagination. This is the power of DRF.
How Do You Add Authentication and Permissions to Your Django API?
Add authentication by installing djangorestframework-simplejwt for JWT tokens, configuring it in settings.py, creating login/register endpoints, and using permission classes to control access at the view level.
# Install JWT authentication
pip install djangorestframework-simplejwt
# myapi/settings.py — Add JWT configuration
from datetime import timedelta
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
],
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
'ROTATE_REFRESH_TOKENS': True,
}
# myapi/urls.py — Add JWT token endpoints
from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('products.urls')),
# JWT Authentication endpoints
path('api/token/', TokenObtainPairView.as_view(),
name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(),
name='token_refresh'),
]
Custom permissions for fine-grained access control:
# products/permissions.py
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission: only the owner of an object can edit it.
Anyone can read (GET, HEAD, OPTIONS).
"""
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 only for the owner
return obj.owner == request.user
class IsAdminOrReadOnly(permissions.BasePermission):
"""
Custom permission: only admin users can create/edit/delete.
All users (including anonymous) can read.
"""
def has_permission(self, request, view):
if request.method in permissions.SAFE_METHODS:
return True
return request.user and request.user.is_staff
# Using custom permissions in your ViewSet
from .permissions import IsAdminOrReadOnly
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
permission_classes = [IsAdminOrReadOnly]
Testing authentication with curl:
# Get JWT tokens
curl -X POST http://localhost:8000/api/token/ \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "yourpassword"}'
# Use the access token to make authenticated requests
curl -X POST http://localhost:8000/api/products/ \
-H "Authorization: Bearer <your_access_token>" \
-H "Content-Type: application/json" \
-d '{"name": "Laptop", "price": 85000, "category": "Electronics"}'
How Do You Handle Relationships, Nested Serializers, and Filtering?
Handle model relationships in DRF by using nested serializers for related objects, PrimaryKeyRelatedField for simple references, and django-filter for query parameter filtering — keeping your API flexible and performant.
Let us extend our example with a Category model and related products:
# products/models.py — Extended with relationships
from django.db import models
from django.conf import settings
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
description = models.TextField(blank=True)
class Meta:
verbose_name_plural = "categories"
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=200)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
category = models.ForeignKey(
Category,
on_delete=models.CASCADE,
related_name='products'
)
owner = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='products'
)
in_stock = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return self.name
# products/serializers.py — Nested serializers
from rest_framework import serializers
from .models import Product, Category
class ProductSerializer(serializers.ModelSerializer):
# Display the category name instead of just the ID
category_name = serializers.CharField(
source='category.name', read_only=True
)
owner_username = serializers.CharField(
source='owner.username', read_only=True
)
class Meta:
model = Product
fields = [
'id', 'name', 'description', 'price',
'category', 'category_name',
'owner', 'owner_username',
'in_stock', 'created_at'
]
read_only_fields = ['owner']
def create(self, validated_data):
"""Automatically set the owner to the current user."""
validated_data['owner'] = self.context['request'].user
return super().create(validated_data)
class CategorySerializer(serializers.ModelSerializer):
# Nest products inside the category response
products = ProductSerializer(many=True, read_only=True)
product_count = serializers.IntegerField(
source='products.count', read_only=True
)
class Meta:
model = Category
fields = ['id', 'name', 'description',
'product_count', 'products']
Filtering setup with django-filter:
pip install django-filter
# products/filters.py
import django_filters
from .models import Product
class ProductFilter(django_filters.FilterSet):
"""
Custom filter for products.
Allows filtering by price range, category, and stock status.
"""
min_price = django_filters.NumberFilter(
field_name='price', lookup_expr='gte'
)
max_price = django_filters.NumberFilter(
field_name='price', lookup_expr='lte'
)
category_name = django_filters.CharFilter(
field_name='category__name', lookup_expr='icontains'
)
class Meta:
model = Product
fields = ['category', 'in_stock', 'min_price',
'max_price', 'category_name']
With this setup, your API supports queries like:
GET /api/products/?min_price=1000&max_price=5000GET /api/products/?category_name=electronics&in_stock=trueGET /api/products/?search=laptop&ordering=-price
How Do You Test and Deploy Your Django REST API?
Test your Django API using DRF's APITestCase for automated tests, the browsable API for manual testing, and deploy to production using Gunicorn, PostgreSQL, and a cloud platform like DigitalOcean or Railway.
Writing automated tests:
# products/tests.py
from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework.test import APIClient
from rest_framework import status
from .models import Product, Category
class ProductAPITest(TestCase):
"""Test suite for the Product API endpoints."""
def setUp(self):
"""Set up test data."""
self.client = APIClient()
self.user = User.objects.create_user(
username='testuser', password='testpass123'
)
self.category = Category.objects.create(
name='Electronics'
)
self.product_data = {
'name': 'Test Laptop',
'description': 'A test product',
'price': '85000.00',
'category': self.category.id,
'in_stock': True,
}
def test_list_products_unauthenticated(self):
"""Anyone can list products."""
response = self.client.get('/api/products/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_create_product_authenticated(self):
"""Authenticated users can create products."""
self.client.force_authenticate(user=self.user)
response = self.client.post(
'/api/products/',
self.product_data,
format='json'
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED
)
self.assertEqual(Product.objects.count(), 1)
self.assertEqual(
Product.objects.first().name, 'Test Laptop'
)
def test_create_product_unauthenticated(self):
"""Unauthenticated users cannot create products."""
response = self.client.post(
'/api/products/',
self.product_data,
format='json'
)
self.assertEqual(
response.status_code,
status.HTTP_401_UNAUTHORIZED
)
# Run tests
python manage.py test products
Production deployment checklist:
# Requirements for production (requirements.txt)
# django==5.1
# djangorestframework==3.15
# djangorestframework-simplejwt==5.4
# django-filter==24.3
# django-cors-headers==4.6
# gunicorn==23.0
# psycopg2-binary==2.9
# python-decouple==3.8
# whitenoise==6.8
# Production settings additions
import os
from decouple import config
DEBUG = False
ALLOWED_HOSTS = ['yourdomain.com', 'api.yourdomain.com']
SECRET_KEY = config('SECRET_KEY')
# CORS for frontend access
INSTALLED_APPS += ['corsheaders']
MIDDLEWARE.insert(1, 'corsheaders.middleware.CorsMiddleware')
CORS_ALLOWED_ORIGINS = [
'https://yourfrontend.com',
]
# PostgreSQL database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': config('DB_NAME'),
'USER': config('DB_USER'),
'PASSWORD': config('DB_PASSWORD'),
'HOST': config('DB_HOST'),
'PORT': config('DB_PORT', default='5432'),
}
}
What the Reddit Community Says
Building APIs with Django generates extensive discussion on Reddit, with developers sharing hard-won lessons from production experience.
Thread: "How do I build an API with Django?" (r/django)
A senior developer provided this advice: "Start with ModelSerializer and ModelViewSet — they give you a full CRUD API in about 10 lines of code. Only drop down to APIView or function-based views when you need custom behavior. I've built APIs serving millions of requests, and 90% of my views are still simple ViewSets."
Thread: "DRF vs FastAPI for new projects in 2026?" (r/python)
A thoughtful comparison: "If you need Django's ORM, admin panel, and authentication system (which most real projects do), use DRF. FastAPI is faster for simple microservices, but when you add all the things DRF gives you for free — auth, admin, permissions, filtering — the development speed difference disappears."
Thread: "Common mistakes when building Django APIs" (r/djangolearning)
An experienced developer listed: "Three biggest mistakes I see: 1) Not using serializer validation and doing it in views instead, 2) Putting business logic in views instead of models or services, 3) Not writing tests. Your serializers should handle ALL validation. Your views should be thin."
Practical Takeaway
To build your first Django REST API today, follow these steps:
- Set up: Create a virtual environment, install Django and DRF
- Model: Define your data model in
models.py - Serialize: Create a
ModelSerializerfor your model - ViewSet: Create a
ModelViewSet— this gives you all CRUD operations - Route: Register your ViewSet with a
DefaultRouter - Auth: Add JWT authentication with
djangorestframework-simplejwt - Test: Write tests for each endpoint using
APITestCase - Deploy: Use Gunicorn + PostgreSQL on DigitalOcean or Railway
The key philosophy with DRF is to use the highest level of abstraction that meets your needs. Start with ViewSets and only drop to lower-level views when you need custom behavior.
For a complete, hands-on learning experience building production-ready APIs, check out Swift Academy's Python Django Full Stack Development course in Pokhara. You will build real API projects from scratch with instructor guidance.
Frequently Asked Questions
Is Django Rest Framework free to use?
Yes, DRF is completely free and open source under the BSD license. You can use it for personal projects, commercial applications, and client work without any licensing fees. The framework is maintained by a strong community and receives regular updates.
Can Django Rest Framework handle high traffic?
Yes. Django and DRF power some of the world's largest websites, including Instagram. For high-traffic APIs, optimize with database indexing, queryset optimization (select_related, prefetch_related), caching with Redis, and horizontal scaling with multiple Gunicorn workers behind a load balancer.
Should I use function-based views or class-based views in DRF?
Use ViewSets with Routers for standard CRUD operations — they minimize boilerplate and generate URLs automatically. Use function-based views with @api_view for simple, one-off endpoints. Use APIView when you need full control over request handling but still want DRF's features.
How do I handle file uploads in Django Rest Framework?
Use FileField or ImageField in your model and serializer. Set parser_classes = [MultiPartParser, FormParser] in your view. For production, use cloud storage like AWS S3 with django-storages instead of storing files on your server.
Can I use Django Rest Framework with a Next.js or React frontend?
Absolutely. This is one of the most popular full stack combinations. Your DRF backend serves JSON data via REST endpoints, and your Next.js frontend consumes those endpoints using fetch or axios. Use django-cors-headers to handle cross-origin requests between your frontend and backend domains.
Build Production-Ready APIs at Swift Academy
Ready to master Django Rest Framework with hands-on projects? Swift Academy's Python Django Full Stack Development course in Pokhara covers everything from Django basics to deploying production APIs. Learn by building real projects with experienced instructors. Enroll now and start building APIs that power real applications.
Related Articles
- Full Stack Developer Roadmap 2026: The Exact Steps from Beginner to Job-Ready
- Python Django Course in Pokhara
- How to Start Freelancing from Nepal in 2026
Suggested Images
- Alt text: "Django Rest Framework browsable API interface showing product endpoints with JSON response data"
- Alt text: "Diagram showing the flow of a REST API request through Django Rest Framework from URL router to serializer to database"
- Alt text: "Code editor showing Django Rest Framework ViewSet and serializer code for a product API"




