Django REST Framework (DRF) is the Web API framework built on Django, providing functions such as request parsing, data verification, serialization, authentication, permissions, paging, and the standard CRUD interface.
Django is mainly responsible for the Web application and database model, while DRF further encapsulates common operations in RESTful API development.
The most important components of DRF:
- Serializer: Request data verification, deserialization and response serialization.
- APIView: Base API View for handling HTTP requests.
- GenericAPIView: encapsulates QuerySet, Serializer, object query and paging logic.
- ViewSet: Group multiple operations of the same resource together.
- Router: Automatically generate URL based on ViewSet.
- Pagination: Handles paging of the list interface.
- Authentication / Permissions: User identity authentication and access rights control.
1. Basic architecture of DRF
Typical DRF request processing flow:
HTTP Request
↓
Django Middleware
↓
URL Routing
↓
DRF APIView
├── Authentication
├── Permissions
├── Throttling
└── Request Parsing
↓
Business Logic / ORM
↓
Serializer
↓
Response / Renderer
↓
HTTP Response
Compared with Django and native View, DRF mainly enhances:
Request: Supports JSON, Form and other request body parsing.Response: Output JSON and other response formats based on Renderer.- Serializer: Input validation and output conversion.
- Authentication、Permissions、Throttling。
- Generic CRUD, paging and filtering mechanisms.
Installation:
pip install djangorestframework
Register:
INSTALLED_APPS = [
# Django Apps
"rest_framework",
"users",
]
Example data model:
# users/models.py
from django.db import models
class UserProfile(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
email = models.EmailField(unique=True)
created_at = models.DateTimeField(auto_now_add=True)
The subsequent examples mainly revolve around this model.
2. Serializer: Data verification and serialization
Serializer is one of the core components of DRF.
Mainly responsible for:
- Serialization: Convert Model Instance and other Python objects into data that can be used in the response.
- Deserialization: Converts request data to validated Python data.
- Validation: Check field type, format and business rules.
- Create / Update: Create or update objects based on verified data.
Serializer
Ordinary Serializer requires manual declaration of fields.
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
name = serializers.CharField(max_length=100)
age = serializers.IntegerField(min_value=0)
email = serializers.EmailField()
Validate input:
serializer = UserSerializer(data={
"name": "Alice",
"age": 25,
"email": "alice@example.com",
})
serializer.is_valid(raise_exception=True)
serializer.validated_data
Common properties and methods:
| API | function |
|---|---|
is_valid() | Validate input |
validated_data | Get verified data |
errors | Get validation error |
data | Get serialized output |
save() | Call create() or update() |
many=True | Handle multiple objects |
ModelSerializer
ModelSerializer can automatically generate Serializer fields and partial validation rules based on Django Model.
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = [
"id",
"name",
"age",
"email",
"created_at",
]
read_only_fields = ["id", "created_at"]
Often more convenient than declaring all fields manually.
Create and Update
serializer = UserProfileSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
Update object:
serializer = UserProfileSerializer(
instance=user,
data=request.data,
partial=True,
)
serializer.is_valid(raise_exception=True)
serializer.save()
Among them:
instance: Object already exists.data: Enter data.partial=True: Allows only some fields to be provided, usually used for PATCH.
ModelSerializer provides common create() and update() implementations by default.
Field Validation
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ["id", "name", "age", "email"]
def validate_age(self, value):
if value < 18:
raise serializers.ValidationError(
"Age must be at least 18."
)
return value
Field level validation:
validate_<field_name>(self, value)
Object level validation:
def validate(self, attrs):
if attrs["name"] == attrs["email"]:
raise serializers.ValidationError(
"Name and email cannot be identical."
)
return attrs
Note: When partially updated, attrs does not necessarily contain all fields, and missing fields should be handled according to the scenario.
read_only / write_only
password = serializers.CharField(write_only=True)
read_only=True: used for output, does not accept client writes.write_only=True: used for input, not included in output.
write_only only controls serialization behavior and does not automatically complete security operations such as password hashing.
Serializer Context
serializer = UserProfileSerializer(
user,
context={"request": request},
)
Can be passed:
self.context["request"]
Get context.
In GenericAPIView, when creating Serializer from get_serializer(), DRF is usually automatically passed in Request and so on Context.
3. APIView: Basic API View
APIView inherits View from Django, and adds Request, Response, authentication, permissions, exception handling and content negotiation capabilities from DRF.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class UserListAPIView(APIView):
def get(self, request):
users = UserProfile.objects.all()
serializer = UserProfileSerializer(
users,
many=True,
)
return Response(serializer.data)
def post(self, request):
serializer = UserProfileSerializer(
data=request.data,
)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(
serializer.data,
status=status.HTTP_201_CREATED,
)
Route:
from django.urls import path
urlpatterns = [
path("users/", UserListAPIView.as_view()),
]
DRF Request
Common properties:
request.data
request.query_params
request.user
request.auth
request.method
Among them:
request.data: The parsed request Body, usually JSON or Form.request.query_params:Query Parameters。request.user: authenticated user.request.auth: Information related to authentication credentials.
Unlike Django native request.POST, request.data can handle request formats such as JSON supported by the corresponding Parser.
DRF Response
return Response(
{"message": "Created"},
status=status.HTTP_201_CREATED,
)
Response is not exactly the same as JsonResponse for Django. DRF's Response is combined with Renderer and Content Negotiation to produce the final response.
APIException
from rest_framework.exceptions import NotFound
raise NotFound("User not found")
Common exceptions:
| Exception | Normal status code |
|---|---|
ValidationError | 400 |
NotAuthenticated | 401 or 403 |
PermissionDenied | 403 |
NotFound | 404 |
MethodNotAllowed | 405 |
Throttled | 429 |
Whether the unauthenticated request ultimately returns 401 or 403 is also related to the behavior of Authentication Class.
APIView is characterized by flexibility, but QuerySet, Serializer and CRUD logic usually requires its own organization.
4. GenericAPIView: general API base class
GenericAPIView inherits APIView and further provides common functionality related to ORM, Serializer, and object queries.
APIView
↓
GenericAPIView
├── get_queryset()
├── get_object()
├── get_serializer()
├── filter_queryset()
└── paginate_queryset()
Common properties:
| Properties | Purpose |
|---|---|
queryset | Default QuerySet |
serializer_class | Default Serializer |
lookup_field | Object query field, default pk |
pagination_class | Paging mode |
filter_backends | Filter backend |
Commonly used methods:
| method | Purpose |
|---|---|
get_queryset() | Get the QuerySet used by the current request |
get_object() | Get a single object, including object permission checks |
get_serializer() | Create Serializer |
get_serializer_class() | Get Serializer Class |
filter_queryset() | Application Filter Backends |
paginate_queryset() | Handle pagination |
GenericAPIView example
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
class UserListAPIView(GenericAPIView):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
def get(self, request):
queryset = self.get_queryset()
serializer = self.get_serializer(
queryset,
many=True,
)
return Response(serializer.data)
Note: The above is a simple example showing the basic method, without manually calling the filtering and paging logic.
If you need the complete list function, it is usually more convenient to use the following ListModelMixin or ListAPIView.
get_queryset()
You can dynamically filter based on users and request parameters:
def get_queryset(self):
queryset = UserProfile.objects.all()
age = self.request.query_params.get("age")
if age is not None:
queryset = queryset.filter(age=age)
return queryset
self.get_queryset() should be used in preference to View, and do not rely directly on the class attribute self.queryset which may have been evaluated and cached.
5. Mixins and Generic Views
DRF provides Mixin that encapsulates the CRUD operation.
| Mixin | Function |
|---|---|
ListModelMixin | list() |
CreateModelMixin | create() |
RetrieveModelMixin | retrieve() |
UpdateModelMixin | update()、partial_update() |
DestroyModelMixin | destroy() |
Mixin itself provides operation methods, but does not automatically map HTTP Method to these operations.
For example:
from rest_framework import generics, mixins
class UserListAPIView(
mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView,
):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
Concrete Generic Views
DRF has combined the common Mixins and GenericAPIView into the concrete View.
| Class | HTTP method |
|---|---|
ListAPIView | GET |
CreateAPIView | POST |
RetrieveAPIView | GET |
UpdateAPIView | PUT / PATCH |
DestroyAPIView | DELETE |
ListCreateAPIView | GET / POST |
RetrieveUpdateDestroyAPIView | GET / PUT / PATCH / DELETE |
For example:
from rest_framework import generics
class UserListCreateAPIView(generics.ListCreateAPIView):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
class UserDetailAPIView(
generics.RetrieveUpdateDestroyAPIView
):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
Route:
urlpatterns = [
path(
"users/",
UserListCreateAPIView.as_view(),
),
path(
"users/<int:pk>/",
UserDetailAPIView.as_view(),
),
]
This makes it possible to implement the common CRUD without having to manually code each HTTP Handler.
Custom save logic
For example, automatically set the current user when creating an object:
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
Commonly used Hook:
perform_create()。perform_update()。perform_destroy()。
Suitable for processing logic related to save behavior such as creators and audit fields.
6. ViewSet: Resource operation collection
ViewSet organizes multiple operations on the same resource into a Class.
The biggest difference from APIView is:
APIView usually defines get(), post(); ViewSet defines list(), retrieve(), create(), etc. Action.
APIView
├── get()
├── post()
└── delete()
ViewSet
├── list()
├── retrieve()
├── create()
├── update()
├── partial_update()
└── destroy()
ViewSet type
| Type | Description |
|---|---|
ViewSet | Basic Action organizational capabilities, excluding default CRUD |
GenericViewSet | ViewSet + GenericAPIView capability |
ReadOnlyModelViewSet | Provide list, retrieve |
ModelViewSet | Provide complete standard CRUD |
ModelViewSet
from rest_framework.viewsets import ModelViewSet
class UserViewSet(ModelViewSet):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
Can provide:
GET /users/ → list
POST /users/ → create
GET /users/1/ → retrieve
PUT /users/1/ → update
PATCH /users/1/ → partial_update
DELETE /users/1/ → destroy
Different Action uses different Serializer
def get_serializer_class(self):
if self.action == "create":
return UserCreateSerializer
return UserProfileSerializer
This is commonly used when creating, updating, and querying require different data structures.
Custom Action
Use @action to define additional resource operations:
from rest_framework.decorators import action
from rest_framework.response import Response
class UserViewSet(ModelViewSet):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
@action(detail=True, methods=["get"])
def summary(self, request, pk=None):
user = self.get_object()
return Response({
"id": user.id,
"name": user.name,
})
Corresponds to:
GET /users/1/summary/
Among them:
detail=True: Acts on a single resource.detail=False: Acts on resource collections.
For ordinary CRUD, ModelViewSet is very efficient; but if the interface is mainly focused on search, calculation or complex business operations, APIView / GenericAPIView may be more intuitive.
7. Router: Automatically generate URL
ViewSet is usually used together with Router.
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(
"users",
UserViewSet,
basename="user",
)
urlpatterns = router.urls
Router automatically generates URL based on Actions of ViewSet.
Main types:
SimpleRouter: Provides standard resource routing.DefaultRouter: On this basis, functions such as API Root View are added, and optional format suffixes can be provided.
basename
basename is used to generate URL Name, for example:
user-list
user-detail
If ViewSet defines queryset, Router can usually automatically infer basename.
If you only override get_queryset() without the queryset attribute, you often need to specify basename explicitly.
The relationship between ViewSet and Router
ModelViewSet
↓
list / retrieve / create / update / destroy
↓
Router
↓
URL Patterns
↓
HTTP Endpoints
Router is responsible for URL mapping, and ViewSet is responsible for Action implementation.
8. Pagination: paging
For large amounts of data, the list API should not return all records at once.
DRF provides three main paging methods.
PageNumberPagination
Access by page number:
GET /users/?page=2
Global configuration:
REST_FRAMEWORK = {
"DEFAULT_PAGINATION_CLASS":
"rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 20,
}
Typical response:
{
"count": 100,
"next": "http://example.com/users/?page=3",
"previous": "http://example.com/users/?page=1",
"results": []
}
LimitOffsetPagination
Using limit and offset:
GET /users/?limit=20&offset=40
Configuration:
from rest_framework.pagination import LimitOffsetPagination
class UserPagination(LimitOffsetPagination):
default_limit = 20
max_limit = 100
CursorPagination
Page turning based on cursor:
from rest_framework.pagination import CursorPagination
class UserCursorPagination(CursorPagination):
page_size = 20
ordering = "-created_at"
Can be used in View:
class UserListAPIView(generics.ListAPIView):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
pagination_class = UserCursorPagination
For stable paging, the sorting should be stable, preferably using unique or nearly unique fields that are not easy to change, combined with appropriate indexes.
Comparison of paging methods
| way | Advantages | limitations |
|---|---|---|
| PageNumber | Simple, supports page numbers | Deep page turning may be slow |
| LimitOffset | Flexible and easy to combine with front-end forms | Large Offset may be slower |
| Cursor | Good for continuous scrolling and dynamic data | Not suitable for arbitrary page jumps |
Note: GenericAPIView and its general list implementation can integrate paging, but when directly inheriting APIView, there will be no automatic paging, and Paginator needs to be called manually.
9. Authentication: Identity authentication
Authentication is responsible for determining who initiated the request.
DRF Common authentication methods:
| way | Features |
|---|---|
| SessionAuthentication | Based on Django Session and Cookie |
| BasicAuthentication | HTTP Basic Auth |
| TokenAuthentication | Basic Token certification provided by DRF |
| JWT | Usually with the help of third-party libraries, such as Simple JWT |
| Custom Authentication | Custom authentication mechanism |
SessionAuthentication
Browser application suitable for use with Django Session.
from rest_framework.authentication import SessionAuthentication
class UserListAPIView(generics.ListAPIView):
authentication_classes = [SessionAuthentication]
permission_classes = [IsAuthenticated]
SessionAuthentication performs a CSRF check on unsafe HTTP requests initiated by authenticated users.
TokenAuthentication
Register first:
INSTALLED_APPS = [
# ...
"rest_framework.authtoken",
]
After running the database migration, you can configure:
from rest_framework.authentication import TokenAuthentication
class UserListAPIView(generics.ListAPIView):
authentication_classes = [TokenAuthentication]
Request example:
Authorization: Token abc123
DRF The built-in base TokenAuthentication does not automatically provide the full Token expiration, refresh and device management mechanisms.
JWT
JWT is the Token format, not the complete authentication scheme that comes with the DRF core.
Common combinations:
Login
↓
Access Token / Refresh Token
↓
Authorization: Bearer <token>
↓
JWT Validation
↓
request.user
JWT authentication is usually achieved through the third party Authentication Class.
Global authentication configuration
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.SessionAuthentication",
"rest_framework.authentication.BasicAuthentication",
],
}
The production environment should select the authentication mechanism based on the actual client type, rather than enabling all authentication methods by default.
10. Permissions: Access permission control
Authentication and Permissions are two independent concepts:
- Authentication: Confirm the current user's identity.
- Permissions: Determine whether the current request can access the resource.
Common Permission Class:
| Permission | meaning |
|---|---|
AllowAny | Allow all requests |
IsAuthenticated | Login required |
IsAdminUser | Requires is_staff=True |
IsAuthenticatedOrReadOnly | Anonymous user read only |
DjangoModelPermissions | Based on Django Model Permissions |
DjangoObjectPermissions | Based on object permissions |
Configuration Permissions
from rest_framework.permissions import IsAuthenticated
class UserListAPIView(generics.ListAPIView):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
permission_classes = [IsAuthenticated]
You can also configure a global default policy:
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticated",
],
}
DRF The default Permission Policy is AllowAny, so access control needs to be configured explicitly according to application security requirements.
Custom permissions
from rest_framework.permissions import BasePermission
class IsOwner(BasePermission):
def has_object_permission(self, request, view, obj):
return obj.owner_id == request.user.id
Common permission methods:
has_permission(self, request, view)
has_object_permission(self, request, view, obj)
has_permission(): View level check.has_object_permission(): Object level check.
Object-Level Permission
In GenericAPIView:
obj = self.get_object()
get_object() invokes object permission checking.
But it should be noted:
list queries do not automatically invoke object-level permission checks on each record.
Therefore, user-visible data usually also needs to be restricted by get_queryset():
def get_queryset(self):
return Document.objects.filter(
owner=self.request.user
)
Ownership should also be explicitly restricted in perform_create() or business logic when objects are created, and creation operations cannot be automatically protected solely by object permissions.
Configure permissions by Action
Common writing methods in ViewSet:
def get_permissions(self):
if self.action in ["create", "update", "partial_update", "destroy"]:
permission_classes = [IsAuthenticated]
else:
permission_classes = [AllowAny]
return [permission() for permission in permission_classes]
Suitable for situations where different Action require different permission rules.
11. Filtering, Ordering and Search
Although it is not the most basic CRUD, the list API almost always involves filtering and sorting.
Custom filtering
class UserListAPIView(generics.ListAPIView):
serializer_class = UserProfileSerializer
def get_queryset(self):
queryset = UserProfile.objects.all()
min_age = self.request.query_params.get("min_age")
if min_age is not None:
queryset = queryset.filter(age__gte=min_age)
return queryset
Query Parameter should be verified first during actual development to avoid server errors caused by invalid integers.
SearchFilter and OrderingFilter
from rest_framework import filters
class UserListAPIView(generics.ListAPIView):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
filter_backends = [
filters.SearchFilter,
filters.OrderingFilter,
]
search_fields = ["name", "email"]
ordering_fields = ["age", "created_at"]
ordering = ["-created_at", "-id"]
Request:
GET /users/?search=alice
GET /users/?ordering=-age
django-filter
More complex field filtering can use the third-party library django-filter:
from django_filters.rest_framework import DjangoFilterBackend
filter_backends = [DjangoFilterBackend]
filterset_fields = ["age", "name"]
In the actual API project, explicitly configuring the fields that allow filtering and sorting is easier to control performance and behavior than opening any fields.
12. Extension mechanism of DRF
DRF has a relatively consistent expansion interface, and many requirements do not require rewriting the complete View.
| extension point | function |
|---|---|
get_queryset() | Dynamic QuerySet |
get_serializer_class() | Dynamic Serializer |
get_serializer_context() | Serializer Context |
perform_create() | Additional operations on creation |
perform_update() | Additional actions when updating |
get_permissions() | Dynamic permissions |
filter_queryset() | Custom filtering process |
pagination_class | Custom paging |
authentication_classes | Custom authentication method |
throttle_classes | Request rate limiting |
exception_handler | Global exception response handling |
Throttling
For example, restrict anonymous access:
REST_FRAMEWORK = {
"DEFAULT_THROTTLE_CLASSES": [
"rest_framework.throttling.AnonRateThrottle",
"rest_framework.throttling.UserRateThrottle",
],
"DEFAULT_THROTTLE_RATES": {
"anon": "100/hour",
"user": "1000/hour",
},
}
DRF Throttling is intended primarily for API usage policy and basic traffic control and should not be used as the only security mechanism against malicious requests or DDoS.
OpenAPI
DRF supports Schema Generation, but if more complete OpenAPI documentation is required with a custom Schema, drf-spectacular is typically used.
For example:
@extend_schema(
parameters=[...],
request=UserCreateSerializer,
responses=UserProfileSerializer,
)
The OpenAPI details fit into a separate drf-spectacular article.
13. How to choose between APIView, GenericAPIView and ViewSet?
This is one of DRF's most important architectural issues to understand.
| Type | level of abstraction | Suitable for the scene |
|---|---|---|
| APIView | low | Non-standard business API, complex processes |
| GenericAPIView | in | Custom interfaces requiring ORM, Serializer and other general capabilities |
| Concrete Generic Views | Middle to high | Standard lists, creation, details and updates |
| ModelViewSet | high | Standard resource CRUD |
| GenericViewSet + Mixins | Can be combined | Only part CRUD Actions is needed |
Example 1: Standard CRUD
GET /products/
POST /products/
GET /products/1/
PATCH /products/1/
DELETE /products/1/
Recommend ModelViewSet.
Example 2: Read-only data API
GET /reports/
GET /reports/1/
ReadOnlyModelViewSet or the corresponding Concrete Generic Views is recommended.
Example 3: Business calculation API
POST /routes/calculate/
If the main process is parameter verification, calling the calculation service and returning the results, without the typical Model CRUD, it is often more straightforward to use APIView or GenericAPIView.
Example 4: Complex search API
GET /search/pois/?keyword=tokyo
If you need custom queries, paging, Serializer and complex filtering, you can choose GenericAPIView.
does not need to force all API to use ModelViewSet in order to reduce the number of lines of code.
14. DRF request life cycle and component relationship
The complete API request process can be summarized as:
Client Request
↓
Django Middleware
↓
URL Router
↓
APIView.dispatch()
↓
DRF Request Initialization
↓
Authentication
↓
Permissions / Throttling
↓
View Handler / ViewSet Action
├── get_queryset()
├── filter_queryset()
├── get_object()
├── paginate_queryset()
└── get_serializer()
↓
is_valid()
↓
Business Logic
↓
ORM / Database
↓
serializer.data
↓
Response
↓
Renderer / HTTP
A distinction needs to be made here:
- Router is responsible for mapping resources URL and Action.
- APIView is responsible for the API request life cycle.
- GenericAPIView provides data query and general interface of Serializer.
- Mixin provides CRUD operation.
- Serializer is responsible for data structure, validation and serialization.
- Authentication and Permissions handle identity and access control respectively.
- Pagination handles segmented return of list results.
The above figure is a conceptual representation of a typical process. Not all Endpoint will call all methods in sequence.
Summary
| Knowledge points | importance |
|---|---|
| Serializer / ModelSerializer | core |
| Validation / create / update | core |
| APIView / Request / Response | core |
| GenericAPIView | core |
| Mixins / Concrete Generic Views | core |
| ModelViewSet / GenericViewSet | core |
| Router / @action | core |
| PageNumber / LimitOffset / Cursor | important |
| Authentication | core |
| Permissions / Object Permissions | core |
| Filtering / Ordering | high frequency |
| get_queryset / get_serializer_class | high frequency |
| perform_create / perform_update | high frequency |
| Throttling | on demand |
| OpenAPI / drf-spectacular | important |
DRF The five most important concepts:
- Serializer: Responsible for data input verification and output serialization, and can manage object creation and updates.
- APIView: Add API-specific Request, Response, authentication and permission lifecycles for Django View.
- GenericAPIView + Mixins: Provides reusable logic of standard ORM CRUD.
- ViewSet + Router: Organize resource operations into Actions and automatically generate URL.
- Authentication + Permissions: Control identity recognition and resource access separately and cannot be confused.
For actual development, it is recommended to give priority to mastering ModelSerializer, GenericAPIView, ModelViewSet, get_queryset(), get_serializer_class(), perform_create() and permission control. These cover most common DRF API development scenarios.