0
# Django REST Framework JSON:API
1
2
A comprehensive Django REST framework adapter that implements the JSON:API specification, transforming Django REST framework's default response format into the structured JSON:API format with proper resource identification, attribute handling, relationship management, and standardized error responses.
3
4
## Package Information
5
6
- **Package Name**: djangorestframework-jsonapi
7
- **Language**: Python
8
- **Installation**: `pip install djangorestframework-jsonapi`
9
- **Dependencies**: Django 4.2+, Django REST Framework 3.15+, inflection 0.5.0+
10
11
## Core Imports
12
13
```python
14
from rest_framework_json_api.serializers import ModelSerializer
15
from rest_framework_json_api.renderers import JSONRenderer
16
from rest_framework_json_api.parsers import JSONParser
17
from rest_framework_json_api.views import ModelViewSet
18
```
19
20
Common import patterns:
21
22
```python
23
# For Django settings
24
from rest_framework_json_api.renderers import JSONRenderer
25
from rest_framework_json_api.parsers import JSONParser
26
27
# For serializers
28
from rest_framework_json_api.serializers import ModelSerializer, HyperlinkedModelSerializer
29
30
# For views
31
from rest_framework_json_api.views import ModelViewSet, ReadOnlyModelViewSet
32
33
# For pagination
34
from rest_framework_json_api.pagination import JsonApiPageNumberPagination
35
36
# For relations
37
from rest_framework_json_api.relations import ResourceRelatedField
38
```
39
40
## Basic Usage
41
42
```python
43
# settings.py - Configure Django REST framework to use JSON:API
44
REST_FRAMEWORK = {
45
'DEFAULT_RENDERER_CLASSES': [
46
'rest_framework_json_api.renderers.JSONRenderer',
47
],
48
'DEFAULT_PARSER_CLASSES': [
49
'rest_framework_json_api.parsers.JSONParser',
50
],
51
'DEFAULT_PAGINATION_CLASS': 'rest_framework_json_api.pagination.JsonApiPageNumberPagination',
52
'PAGE_SIZE': 20
53
}
54
55
# serializers.py - Create JSON:API compatible serializers
56
from rest_framework_json_api import serializers
57
from myapp.models import Article, Author
58
59
class ArticleSerializer(serializers.ModelSerializer):
60
class Meta:
61
model = Article
62
fields = ['title', 'content', 'author', 'created_at']
63
64
class AuthorSerializer(serializers.ModelSerializer):
65
class Meta:
66
model = Author
67
fields = ['name', 'email', 'articles']
68
69
# views.py - Create JSON:API compatible views
70
from rest_framework_json_api import views
71
from rest_framework_json_api.pagination import JsonApiPageNumberPagination
72
73
class ArticleViewSet(views.ModelViewSet):
74
queryset = Article.objects.all()
75
serializer_class = ArticleSerializer
76
pagination_class = JsonApiPageNumberPagination
77
78
# This creates JSON:API compliant responses like:
79
# {
80
# "data": [{
81
# "type": "articles",
82
# "id": "1",
83
# "attributes": {
84
# "title": "Sample Article",
85
# "content": "Article content...",
86
# "created-at": "2023-01-01T12:00:00Z"
87
# },
88
# "relationships": {
89
# "author": {
90
# "data": {"type": "authors", "id": "5"}
91
# }
92
# }
93
# }],
94
# "meta": {"pagination": {"page": 1, "pages": 10, "count": 200}}
95
# }
96
```
97
98
## Architecture
99
100
The package extends Django REST framework through several key components:
101
102
- **Serializers**: Transform Django model data to/from JSON:API resource objects with attributes and relationships
103
- **Renderers**: Convert Django REST framework responses to JSON:API format with proper data, meta, and links sections
104
- **Parsers**: Parse JSON:API requests into Django REST framework format for processing
105
- **Views**: Enhanced ViewSets with JSON:API features like include parameter support and automatic prefetching
106
- **Relations**: Resource relationship fields that handle JSON:API resource identifier objects
107
- **Pagination**: JSON:API compliant pagination with proper meta and links sections
108
- **Filtering**: JSON:API compliant filtering and sorting with validation
109
- **Exception Handling**: Transform errors into JSON:API error format
110
111
The design maintains full compatibility with Django REST framework patterns while providing JSON:API specification compliance.
112
113
## Capabilities
114
115
### Serializers
116
117
JSON:API compatible serializers that transform Django models into JSON:API resource objects with proper attributes, relationships, and resource identification. Includes support for polymorphic models, sparse fieldsets, and all standard Django REST framework serializer features.
118
119
```python { .api }
120
class ModelSerializer(rest_framework.serializers.ModelSerializer): ...
121
class HyperlinkedModelSerializer(rest_framework.serializers.HyperlinkedModelSerializer): ...
122
class ResourceIdentifierObjectSerializer(BaseSerializer): ...
123
class SparseFieldsetsMixin: ...
124
class IncludedResourcesValidationMixin: ...
125
class ReservedFieldNamesMixin: ...
126
class PolymorphicModelSerializer(ModelSerializer): ...
127
```
128
129
[Serializers](./serializers.md)
130
131
### Renderers and Parsers
132
133
JSON:API renderers convert Django REST framework responses to JSON:API format, while parsers handle incoming JSON:API requests. Supports proper resource object structure, relationship handling, meta information, and error formatting.
134
135
```python { .api }
136
class JSONRenderer(renderers.JSONRenderer): ...
137
class JSONParser(parsers.JSONParser): ...
138
```
139
140
[Renderers and Parsers](./renderers-parsers.md)
141
142
### Views and ViewSets
143
144
Enhanced Django REST framework views with JSON:API features including automatic include parameter handling, relationship views, prefetching optimization, and JSON:API response formatting.
145
146
```python { .api }
147
class ModelViewSet(PreloadIncludesMixin, viewsets.ModelViewSet): ...
148
class ReadOnlyModelViewSet(PreloadIncludesMixin, viewsets.ReadOnlyModelViewSet): ...
149
class RelationshipView(generics.GenericAPIView): ...
150
class RelatedMixin: ...
151
class PreloadIncludesMixin: ...
152
class AutoPrefetchMixin: ...
153
```
154
155
[Views](./views.md)
156
157
### Relations and Resource Fields
158
159
Resource relationship fields that handle JSON:API resource identifier objects, hyperlinked relationships, and relationship data management with support for both to-one and to-many relationships.
160
161
```python { .api }
162
class ResourceRelatedField(RelatedField): ...
163
class PolymorphicResourceRelatedField(ResourceRelatedField): ...
164
class HyperlinkedMixin: ...
165
class HyperlinkedRelatedField: ...
166
class SerializerMethodResourceRelatedField: ...
167
class ManySerializerMethodResourceRelatedField: ...
168
class SerializerMethodHyperlinkedRelatedField: ...
169
class ManySerializerMethodHyperlinkedRelatedField: ...
170
```
171
172
[Relations](./relations.md)
173
174
### Pagination
175
176
JSON:API compliant pagination classes that provide proper meta information and navigation links, supporting both page number and limit/offset pagination styles.
177
178
```python { .api }
179
class JsonApiPageNumberPagination(PageNumberPagination): ...
180
class JsonApiLimitOffsetPagination(LimitOffsetPagination): ...
181
```
182
183
[Pagination](./pagination.md)
184
185
### Filtering and Sorting
186
187
JSON:API compliant filtering and sorting with proper validation, field name formatting, and integration with django-filter for advanced filtering capabilities.
188
189
```python { .api }
190
class OrderingFilter(rest_framework.filters.OrderingFilter): ...
191
class DjangoFilterBackend(django_filters.rest_framework.DjangoFilterBackend): ...
192
```
193
194
[Filtering](./filtering.md)
195
196
### Exception Handling and Utilities
197
198
JSON:API compliant error formatting, field name formatting utilities, resource type management, and settings configuration for customizing JSON:API behavior.
199
200
```python { .api }
201
def exception_handler(exc, context): ...
202
class Conflict(exceptions.APIException): ...
203
class JSONAPIMetadata(SimpleMetadata): ...
204
class JSONAPISettings: ...
205
```
206
207
[Exception Handling and Utilities](./exceptions-utilities.md)
208
209
## Configuration
210
211
Key settings for customizing JSON:API behavior:
212
213
```python
214
# settings.py
215
JSON_API_FORMAT_FIELD_NAMES = True # Convert snake_case to kebab-case
216
JSON_API_FORMAT_TYPES = True # Format resource type names
217
JSON_API_PLURALIZE_TYPES = True # Pluralize resource type names
218
JSON_API_UNIFORM_EXCEPTIONS = True # Use JSON:API error format everywhere
219
```