Django Rest Framework (DRF) -
Complete Beginner to Advanced Guide
Welcome to the Django Rest Framework (DRF) guide. This document is written for absolute
beginners who may know Django basics but are new to DRF. It explains key concepts step
by step with examples and code snippets. By the end, you'll be able to build secure APIs
using DRF.
1. What is an API?
API (Application Programming Interface) allows communication between two systems.
In web development, APIs usually return data in JSON format that frontend/mobile apps
can use.
Example: A Book API can return a list of books as JSON:
[{'id':1, 'title':'Django Basics', 'author':'Alice'}]
2. Why Django Rest Framework (DRF)?
Django alone is great for web apps but not specialized for APIs.
DRF provides tools for:
- Serializing data (Python <-> JSON)
- Building CRUD APIs quickly
- Authentication & Permissions
- Browsable API (nice web interface for testing)
3. Setting up DRF
Install: pip install djangorestframework
Add 'rest_framework' to INSTALLED_APPS in settings.py
Start an app (e.g., books) to build APIs.
4. Models
Models define database tables in Django.
Example (books/models.py):
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return self.title
5. What are Serializers?
Serializers convert complex data (like Django models) into JSON and back.
Think of it as a translator between Python objects and JSON.
Example (books/serializers.py):
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
6. Views (Function-based)
Views handle HTTP requests (GET, POST, PUT, DELETE).
Example (books/views.py):
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Book
from .serializers import BookSerializer
@api_view(['GET'])
def book_list(request):
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
7. Views (Class-based with ViewSet)
ViewSets reduce boilerplate code and provide CRUD automatically.
Example (books/views.py):
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
8. Routers
Routers automatically create URLs for ViewSets.
Example (books/urls.py):
from rest_framework.routers import DefaultRouter
from .views import BookViewSet
router = DefaultRouter()
router.register(r'books', BookViewSet)
urlpatterns = router.urls
9. Permissions
Permissions decide WHO can access an API.
Example: Only logged-in users can access the API.
from rest_framework.permissions import IsAuthenticated
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
permission_classes = [IsAuthenticated]
10. Authentication with JWT
Authentication proves WHO the user is.
JWT (JSON Web Tokens) are widely used for APIs.
Steps:
- Install: pip install djangorestframework-simplejwt
- Add JWTAuthentication in settings.py
- Add URLs:
from rest_framework_simplejwt.views import TokenObtainPairView,
TokenRefreshView
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
11. Testing API
1. Create superuser: python manage.py createsuperuser
2. Get token: POST to /api/token/ with username & password
3. Use token in Authorization header: Bearer <token>
4. Access endpoints like /books/ and /books/<id>/
12. Summary
Models: Define data structure
Serializers: Convert Python <-> JSON
Views: Handle requests
ViewSets + Routers: Shortcut for CRUD APIs
Permissions & Authentication: Secure APIs
JWT: Popular token-based authentication