or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

exceptions-utilities.mdfiltering.mdindex.mdpagination.mdrelations.mdrenderers-parsers.mdserializers.mdviews.md
tile.json

tessl/pypi-djangorestframework-jsonapi

A Django REST framework API adapter for the JSON:API spec.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/djangorestframework-jsonapi@8.0.x

To install, run

npx @tessl/cli install tessl/pypi-djangorestframework-jsonapi@8.0.0

index.mddocs/

Django REST Framework JSON:API

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.

Package Information

  • Package Name: djangorestframework-jsonapi
  • Language: Python
  • Installation: pip install djangorestframework-jsonapi
  • Dependencies: Django 4.2+, Django REST Framework 3.15+, inflection 0.5.0+

Core Imports

from rest_framework_json_api.serializers import ModelSerializer
from rest_framework_json_api.renderers import JSONRenderer
from rest_framework_json_api.parsers import JSONParser
from rest_framework_json_api.views import ModelViewSet

Common import patterns:

# For Django settings
from rest_framework_json_api.renderers import JSONRenderer
from rest_framework_json_api.parsers import JSONParser

# For serializers
from rest_framework_json_api.serializers import ModelSerializer, HyperlinkedModelSerializer

# For views
from rest_framework_json_api.views import ModelViewSet, ReadOnlyModelViewSet

# For pagination
from rest_framework_json_api.pagination import JsonApiPageNumberPagination

# For relations
from rest_framework_json_api.relations import ResourceRelatedField

Basic Usage

# settings.py - Configure Django REST framework to use JSON:API
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework_json_api.renderers.JSONRenderer',
    ],
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework_json_api.parsers.JSONParser',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework_json_api.pagination.JsonApiPageNumberPagination',
    'PAGE_SIZE': 20
}

# serializers.py - Create JSON:API compatible serializers
from rest_framework_json_api import serializers
from myapp.models import Article, Author

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ['title', 'content', 'author', 'created_at']

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ['name', 'email', 'articles']

# views.py - Create JSON:API compatible views
from rest_framework_json_api import views
from rest_framework_json_api.pagination import JsonApiPageNumberPagination

class ArticleViewSet(views.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    pagination_class = JsonApiPageNumberPagination

# This creates JSON:API compliant responses like:
# {
#   "data": [{
#     "type": "articles",
#     "id": "1",
#     "attributes": {
#       "title": "Sample Article",
#       "content": "Article content...",
#       "created-at": "2023-01-01T12:00:00Z"
#     },
#     "relationships": {
#       "author": {
#         "data": {"type": "authors", "id": "5"}
#       }
#     }
#   }],
#   "meta": {"pagination": {"page": 1, "pages": 10, "count": 200}}
# }

Architecture

The package extends Django REST framework through several key components:

  • Serializers: Transform Django model data to/from JSON:API resource objects with attributes and relationships
  • Renderers: Convert Django REST framework responses to JSON:API format with proper data, meta, and links sections
  • Parsers: Parse JSON:API requests into Django REST framework format for processing
  • Views: Enhanced ViewSets with JSON:API features like include parameter support and automatic prefetching
  • Relations: Resource relationship fields that handle JSON:API resource identifier objects
  • Pagination: JSON:API compliant pagination with proper meta and links sections
  • Filtering: JSON:API compliant filtering and sorting with validation
  • Exception Handling: Transform errors into JSON:API error format

The design maintains full compatibility with Django REST framework patterns while providing JSON:API specification compliance.

Capabilities

Serializers

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.

class ModelSerializer(rest_framework.serializers.ModelSerializer): ...
class HyperlinkedModelSerializer(rest_framework.serializers.HyperlinkedModelSerializer): ...
class ResourceIdentifierObjectSerializer(BaseSerializer): ...
class SparseFieldsetsMixin: ...
class IncludedResourcesValidationMixin: ...
class ReservedFieldNamesMixin: ...
class PolymorphicModelSerializer(ModelSerializer): ...

Serializers

Renderers and Parsers

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.

class JSONRenderer(renderers.JSONRenderer): ...
class JSONParser(parsers.JSONParser): ...

Renderers and Parsers

Views and ViewSets

Enhanced Django REST framework views with JSON:API features including automatic include parameter handling, relationship views, prefetching optimization, and JSON:API response formatting.

class ModelViewSet(PreloadIncludesMixin, viewsets.ModelViewSet): ...
class ReadOnlyModelViewSet(PreloadIncludesMixin, viewsets.ReadOnlyModelViewSet): ...
class RelationshipView(generics.GenericAPIView): ...
class RelatedMixin: ...
class PreloadIncludesMixin: ...
class AutoPrefetchMixin: ...

Views

Relations and Resource Fields

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.

class ResourceRelatedField(RelatedField): ...
class PolymorphicResourceRelatedField(ResourceRelatedField): ...
class HyperlinkedMixin: ...
class HyperlinkedRelatedField: ...
class SerializerMethodResourceRelatedField: ...
class ManySerializerMethodResourceRelatedField: ...
class SerializerMethodHyperlinkedRelatedField: ...
class ManySerializerMethodHyperlinkedRelatedField: ...

Relations

Pagination

JSON:API compliant pagination classes that provide proper meta information and navigation links, supporting both page number and limit/offset pagination styles.

class JsonApiPageNumberPagination(PageNumberPagination): ...
class JsonApiLimitOffsetPagination(LimitOffsetPagination): ...

Pagination

Filtering and Sorting

JSON:API compliant filtering and sorting with proper validation, field name formatting, and integration with django-filter for advanced filtering capabilities.

class OrderingFilter(rest_framework.filters.OrderingFilter): ...
class DjangoFilterBackend(django_filters.rest_framework.DjangoFilterBackend): ...

Filtering

Exception Handling and Utilities

JSON:API compliant error formatting, field name formatting utilities, resource type management, and settings configuration for customizing JSON:API behavior.

def exception_handler(exc, context): ...
class Conflict(exceptions.APIException): ...
class JSONAPIMetadata(SimpleMetadata): ...
class JSONAPISettings: ...

Exception Handling and Utilities

Configuration

Key settings for customizing JSON:API behavior:

# settings.py
JSON_API_FORMAT_FIELD_NAMES = True  # Convert snake_case to kebab-case
JSON_API_FORMAT_TYPES = True        # Format resource type names
JSON_API_PLURALIZE_TYPES = True     # Pluralize resource type names
JSON_API_UNIFORM_EXCEPTIONS = True  # Use JSON:API error format everywhere