Django REST Framework: The Complete Guide
Django REST Framework (DRF) is the gold standard for building web APIs in Python. It provides powerful serialization, flexible authentication, and browsable APIs out of the box.
Setting Up
pip install djangorestframework
pip install django-filter
pip install drf-spectacular # OpenAPI documentation
Serializers
Serializers convert complex data types like Django querysets into Python data types that can be rendered as JSON. They also handle validation and deserialization.
from rest_framework import serializers
from .models import BlogPost
class BlogPostSerializer(serializers.ModelSerializer):
author_name = serializers.CharField(source='author.username', read_only=True)
like_count = serializers.SerializerMethodField()
class Meta:
model = BlogPost
fields = ['id', 'title', 'slug', 'excerpt', 'content',
'author_name', 'like_count', 'published_date']
read_only_fields = ['slug', 'published_date']
def get_like_count(self, obj):
return obj.likes.count()
def validate_title(self, value):
if len(value) < 10:
raise serializers.ValidationError("Title must be at least 10 characters.")
return value
ViewSets and Routers
from rest_framework import viewsets, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
class BlogPostViewSet(viewsets.ModelViewSet):
queryset = BlogPost.objects.filter(status='published')
serializer_class = BlogPostSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
filterset_fields = ['category', 'tags']
search_fields = ['title', 'content']
ordering_fields = ['published_date', 'views']
@action(detail=True, methods=['post'])
def like(self, request, pk=None):
post = self.get_object()
post.likes.get_or_create(user=request.user)
return Response({'status': 'liked'})
Testing Your API
DRF includes a powerful test client. Always test your serializer validation, permissions, and edge cases.
Documentation
Use drf-spectacular to auto-generate OpenAPI 3.0 documentation. This gives you interactive Swagger UI and ReDoc pages that stay synchronized with your code.
💬 Comments (0)
No comments yet. Be the first to share your thoughts!
Leave a Comment
Your comment will be reviewed before it appears publicly.