Django REST Framework
Django REST Framework (DRF) is the most popular library for building REST APIs in Django. It provides serializers for data validation and transformation, v...
Production REST APIs with Django REST Framework
Django REST Framework (DRF) is the most popular library for building REST APIs in Django. It provides serializers for data validation and transformation, viewsets for CRUD operations, authentication backends, permissions, pagination, and a browsable API interface for development.
Install with pip install djangorestframework. Add 'rest_framework' to INSTALLED_APPS in settings.py.
Serializers are DRF's core — they convert Python objects to JSON and validate incoming data: from rest_framework import serializers from .models import Article
class ArticleSerializer(serializers.ModelSerializer): author_name = serializers.SerializerMethodField()
class Meta: model = Article fields = ['id', 'title', 'content', 'published_at', 'author_name'] read_only_fields = ['id', 'published_at']
def get_author_name(self, obj): return obj.author.get_full_name()
ViewSets combine list, create, retrieve, update, and destroy into one class: from rest_framework import viewsets, permissions from .models import Article from .serializers import ArticleSerializer
class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.select_related('author').all() serializer_class = ArticleSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def perform_create(self, serializer): serializer.save(author=self.request.user)
Routers generate all URL patterns automatically: from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'articles', ArticleViewSet) urlpatterns = router.urls # Generates: GET/POST /articles/, GET/PUT/PATCH/DELETE /articles/{id}/
Authentication options in DRF: SessionAuthentication (cookies), BasicAuthentication, TokenAuthentication. For JWT, use djangorestframework-simplejwt: pip install djangorestframework-simplejwt # Add to settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework_simplejwt.authentication.JWTAuthentication'], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 20 }
Filtering with django-filter: from django_filters.rest_framework import DjangoFilterBackend class ArticleViewSet(viewsets.ModelViewSet): filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] filterset_fields = ['status', 'category'] search_fields = ['title', 'content'] ordering_fields = ['published_at', 'title']
Practical tip: Use generic views (generics.ListCreateAPIView, generics.RetrieveUpdateDestroyAPIView) when you need more control than ModelViewSet but less code than plain APIView. Each generic view maps to specific HTTP methods.
Exam tip: DRF serializer validation runs in two stages: field-level validation (validate_fieldname methods) and object-level validation (validate method). The validate method receives the entire data dict and is used for cross-field validation.