0
# Django REST Framework
1
2
A powerful and flexible toolkit for building Web APIs in Django applications. Django REST framework provides comprehensive features for creating RESTful APIs including serialization, authentication, permissions, content negotiation, pagination, filtering, and a browsable API interface.
3
4
## Package Information
5
6
- **Package Name**: djangorestframework
7
- **Language**: Python
8
- **Installation**: `pip install djangorestframework`
9
- **Dependencies**: `django>=4.2`
10
- **Python Requirements**: `>=3.9`
11
12
## Core Imports
13
14
```python
15
import rest_framework
16
from rest_framework import serializers, viewsets, permissions, status
17
from rest_framework.decorators import api_view, action
18
from rest_framework.response import Response
19
from rest_framework.views import APIView
20
```
21
22
## Basic Usage
23
24
```python
25
from rest_framework import serializers, viewsets, permissions
26
from rest_framework.response import Response
27
from django.contrib.auth.models import User
28
29
# Create a serializer
30
class UserSerializer(serializers.ModelSerializer):
31
class Meta:
32
model = User
33
fields = ['id', 'username', 'email']
34
35
# Create a viewset
36
class UserViewSet(viewsets.ModelViewSet):
37
queryset = User.objects.all()
38
serializer_class = UserSerializer
39
permission_classes = [permissions.IsAuthenticated]
40
41
# Or use function-based views
42
from rest_framework.decorators import api_view
43
44
@api_view(['GET', 'POST'])
45
def user_list(request):
46
if request.method == 'GET':
47
users = User.objects.all()
48
serializer = UserSerializer(users, many=True)
49
return Response(serializer.data)
50
elif request.method == 'POST':
51
serializer = UserSerializer(data=request.data)
52
if serializer.is_valid():
53
serializer.save()
54
return Response(serializer.data, status=status.HTTP_201_CREATED)
55
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
56
```
57
58
## Architecture
59
60
Django REST Framework follows a layered architecture designed around Django's philosophy:
61
62
- **Serializers**: Convert between Python objects and JSON/XML data formats
63
- **Views/ViewSets**: Handle HTTP requests and coordinate with serializers
64
- **Permissions**: Control access to API endpoints
65
- **Authentication**: Identify users making requests
66
- **Parsers/Renderers**: Handle content negotiation for different formats
67
- **Routers**: Generate URL patterns for ViewSets automatically
68
69
The framework emphasizes flexibility through class-based views and mixins, enabling everything from simple function-based views to complex ViewSets with automatic URL routing.
70
71
## Capabilities
72
73
### Serializers
74
75
Core serialization framework for converting between Python objects and JSON/XML data. Handles validation, type conversion, and nested relationships with comprehensive field types and custom validation logic.
76
77
```python { .api }
78
class Serializer(BaseSerializer):
79
def __init__(self, instance=None, data=empty, **kwargs): ...
80
def is_valid(self, raise_exception=False): ...
81
def save(self): ...
82
def create(self, validated_data): ...
83
def update(self, instance, validated_data): ...
84
85
class ModelSerializer(Serializer):
86
class Meta:
87
model = None
88
fields = None
89
```
90
91
[Serializers](./serializers.md)
92
93
### Views and ViewSets
94
95
Class-based views and ViewSets for handling HTTP requests. Includes generic views for common patterns, mixins for modular functionality, and ViewSets for automatic URL routing.
96
97
```python { .api }
98
class APIView(View):
99
authentication_classes = []
100
permission_classes = []
101
parser_classes = []
102
renderer_classes = []
103
104
def dispatch(self, request, *args, **kwargs): ...
105
106
class ViewSet(ViewSetMixin, APIView):
107
def list(self, request): ...
108
def create(self, request): ...
109
110
class ModelViewSet(GenericViewSet):
111
queryset = None
112
serializer_class = None
113
```
114
115
[Views and ViewSets](./views-viewsets.md)
116
117
### Authentication and Permissions
118
119
Security framework providing authentication backends and permission classes. Supports session authentication, token authentication, and custom authentication with granular permission control.
120
121
```python { .api }
122
class BaseAuthentication:
123
def authenticate(self, request): ...
124
def authenticate_header(self, request): ...
125
126
class BasePermission:
127
def has_permission(self, request, view): ...
128
def has_object_permission(self, request, view, obj): ...
129
130
class TokenAuthentication(BaseAuthentication): ...
131
class IsAuthenticated(BasePermission): ...
132
```
133
134
[Authentication and Permissions](./auth-permissions.md)
135
136
### Fields and Validation
137
138
Comprehensive field types for data validation and serialization. Includes basic types, specialized fields for files/images, and relationship fields with custom validation support.
139
140
```python { .api }
141
class Field:
142
def __init__(self, **kwargs): ...
143
def to_representation(self, value): ...
144
def to_internal_value(self, data): ...
145
def validate(self, value): ...
146
147
class CharField(Field): ...
148
class IntegerField(Field): ...
149
class DateTimeField(Field): ...
150
class SerializerMethodField(Field): ...
151
```
152
153
[Fields and Validation](./fields-validation.md)
154
155
### Generic Views and Mixins
156
157
Pre-built generic views and mixins for common API patterns. Provides CRUD operations, pagination, and filtering with minimal code.
158
159
```python { .api }
160
class GenericAPIView(APIView):
161
queryset = None
162
serializer_class = None
163
164
def get_queryset(self): ...
165
def get_object(self): ...
166
167
class ListAPIView(GenericAPIView): ...
168
class CreateAPIView(GenericAPIView): ...
169
class RetrieveUpdateDestroyAPIView(GenericAPIView): ...
170
```
171
172
[Generic Views and Mixins](./generic-views.md)
173
174
### Request and Response
175
176
Enhanced request and response objects providing consistent data access and content negotiation across different formats.
177
178
```python { .api }
179
class Request:
180
@property
181
def data(self): ...
182
@property
183
def query_params(self): ...
184
185
class Response(SimpleTemplateResponse):
186
def __init__(self, data=None, status=None, template_name=None, headers=None, exception=False, content_type=None): ...
187
```
188
189
[Request and Response](./request-response.md)
190
191
### Pagination and Filtering
192
193
Built-in pagination styles and filtering backends for managing large datasets with search and ordering capabilities.
194
195
```python { .api }
196
class PageNumberPagination(BasePagination):
197
page_size = None
198
page_query_param = 'page'
199
200
def paginate_queryset(self, queryset, request, view=None): ...
201
202
class SearchFilter(BaseFilterBackend):
203
search_param = 'search'
204
205
def filter_queryset(self, request, queryset, view): ...
206
```
207
208
[Pagination and Filtering](./pagination-filtering.md)
209
210
### Routers and URL Patterns
211
212
Automatic URL pattern generation for ViewSets with support for nested routes and custom actions.
213
214
```python { .api }
215
class SimpleRouter(BaseRouter):
216
def register(self, prefix, viewset, basename=None): ...
217
def get_urls(self): ...
218
219
class DefaultRouter(SimpleRouter):
220
include_root_view = True
221
include_format_suffixes = True
222
```
223
224
[Routers and URL Patterns](./routers-urls.md)
225
226
### Status Codes and Exceptions
227
228
Complete HTTP status code constants and structured exception classes for consistent error handling.
229
230
```python { .api }
231
# Constants
232
HTTP_200_OK = 200
233
HTTP_201_CREATED = 201
234
HTTP_400_BAD_REQUEST = 400
235
HTTP_404_NOT_FOUND = 404
236
237
# Exception classes
238
class APIException(Exception):
239
status_code = None
240
default_detail = None
241
242
class ValidationError(APIException): ...
243
class NotFound(APIException): ...
244
```
245
246
[Status Codes and Exceptions](./status-exceptions.md)
247
248
### Testing Utilities
249
250
Comprehensive testing tools including API client, request factory, and test case classes for thorough API testing.
251
252
```python { .api }
253
class APIClient(APIRequestFactory, DjangoClient):
254
def force_authenticate(self, user=None, token=None): ...
255
def get(self, path, data=None, **extra): ...
256
def post(self, path, data=None, format=None, **extra): ...
257
258
class APITestCase(testcases.TestCase):
259
client_class = APIClient
260
```
261
262
[Testing Utilities](./testing.md)
263
264
### Decorators and Function-Based Views
265
266
Essential decorators for function-based views and ViewSet customization, including API view creation, policy settings, and custom action definitions.
267
268
```python { .api }
269
def api_view(http_method_names=None):
270
"""Convert function-based view into APIView subclass."""
271
272
def action(methods=None, detail=None, url_path=None, url_name=None, **kwargs):
273
"""Mark ViewSet method as routable action."""
274
275
def permission_classes(permission_classes):
276
"""Set permission classes for function-based views."""
277
278
def authentication_classes(authentication_classes):
279
"""Set authentication classes for function-based views."""
280
281
def throttle_classes(throttle_classes):
282
"""Set throttle classes for function-based views."""
283
284
class MethodMapper(dict):
285
"""Enables mapping HTTP methods to different ViewSet methods."""
286
```
287
288
[Decorators and Function-Based Views](./decorators.md)
289
290
### Content Negotiation
291
292
Parser and renderer classes for handling multiple content types with automatic format detection and conversion.
293
294
```python { .api }
295
class BaseParser:
296
media_type = None
297
298
def parse(self, stream, media_type=None, parser_context=None): ...
299
300
class BaseRenderer:
301
media_type = None
302
303
def render(self, data, accepted_media_type=None, renderer_context=None): ...
304
```
305
306
[Content Negotiation](./content-negotiation.md)
307
308
## Types
309
310
```python { .api }
311
# Core constants
312
empty = object() # Sentinel for no data provided
313
ALL_FIELDS = '__all__' # Include all model fields
314
315
# Exception types
316
class ErrorDetail(str):
317
def __new__(cls, string, code=None): ...
318
319
# Utility types
320
class ReturnDict(dict):
321
def __init__(self, *args, **kwargs): ...
322
323
class ReturnList(list):
324
def __init__(self, *args, **kwargs): ...
325
```