CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-djangorestframework-jsonapi

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

Pending
Overview
Eval results
Files

serializers.mddocs/

Serializers

JSON:API compatible serializers that transform Django models into JSON:API resource objects with proper attributes, relationships, and resource identification. These serializers extend Django REST framework serializers with JSON:API specific functionality.

Capabilities

ModelSerializer

Enhanced ModelSerializer that automatically handles JSON:API resource object formatting, field name conversion, and relationship handling.

class ModelSerializer(rest_framework.serializers.ModelSerializer):
    """
    JSON:API compatible ModelSerializer with automatic resource object formatting.
    
    Inherits all Django REST framework ModelSerializer functionality while adding:
    - Automatic resource type detection from model
    - JSON:API attribute and relationship formatting
    - Support for sparse fieldsets via fields[type] query parameter
    - Integration with JSON:API renderer for proper output format
    """
    
    class Meta:
        model = None  # Django model class
        fields = []   # List of fields to include
        resource_name = None  # Override resource type name

Usage example:

from rest_framework_json_api import serializers
from myapp.models import Article

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ['title', 'content', 'author', 'created_at']
        
# Automatically generates JSON:API resource objects:
# {
#   "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"}}
#   }
# }

HyperlinkedModelSerializer

Enhanced HyperlinkedModelSerializer with JSON:API hyperlink support in relationships and resource links.

class HyperlinkedModelSerializer(rest_framework.serializers.HyperlinkedModelSerializer):
    """
    JSON:API compatible HyperlinkedModelSerializer with hyperlinked relationships.
    
    Extends HyperlinkedModelSerializer to generate proper JSON:API links in:
    - Resource object links section
    - Relationship links (self and related)
    - Top-level links for collections
    """
    
    class Meta:
        model = None
        fields = []
        extra_kwargs = {}  # Field-specific options

ResourceIdentifierObjectSerializer

Serializer for JSON:API resource identifier objects used in relationships.

class ResourceIdentifierObjectSerializer(BaseSerializer):
    """
    Serializer for JSON:API resource identifier objects.
    
    Handles resource identifier objects in the format:
    {"type": "resource-type", "id": "123"}
    
    Used internally by relationship fields.
    """
    
    model_class = None  # Model class this serializer represents
    
    def __init__(self, model_class=None, *args, **kwargs):
        """
        Initialize serializer with model class.
        
        Args:
            model_class: Django model class for this resource type
        """
    
    def to_representation(self, instance):
        """
        Convert model instance to resource identifier object.
        
        Args:
            instance: Django model instance
            
        Returns:
            dict: Resource identifier with type and id
        """
    
    def to_internal_value(self, data):
        """
        Convert resource identifier to model instance.
        
        Args:
            data: Resource identifier object dict
            
        Returns:
            Model instance
            
        Raises:
            ValidationError: If type doesn't match or object doesn't exist
        """

SparseFieldsetsMixin

Mixin that adds support for JSON:API sparse fieldsets through the fields query parameter.

class SparseFieldsetsMixin:
    """
    Mixin for sparse fieldsets support via fields[type] query parameter.
    
    Implements JSON:API sparse fieldsets specification:
    https://jsonapi.org/format/#fetching-sparse-fieldsets
    
    Usage: GET /articles?fields[articles]=title,author
    """
    
    @property
    def _readable_fields(self):
        """
        Filter readable fields based on sparse fieldset query parameter.
        
        Returns:
            Filtered field list based on fields[resource-type] parameter
        """

Usage example:

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

# With request: GET /articles?fields[articles]=title,author
# Only returns title and author fields in attributes

IncludedResourcesValidationMixin

Mixin that validates include parameter against serializer configuration.

class IncludedResourcesValidationMixin:
    """
    Mixin for validating include query parameter against serializer configuration.
    
    Ensures that requested include paths are supported by the serializer's
    included_serializers configuration.
    
    Raises ParseError for unsupported include paths.
    """

ReservedFieldNamesMixin

Mixin that prevents use of reserved field names.

class ReservedFieldNamesMixin:
    """
    Mixin that ensures reserved field names are not used in serializers.
    
    Reserved field names include: 'meta', 'results', 'type', and others
    that conflict with JSON:API specification.
    
    Raises AssertionError if reserved field names are used.
    """

PolymorphicModelSerializer

Serializer for polymorphic models that can represent multiple resource types.

class PolymorphicModelSerializer(ModelSerializer):
    """
    Serializer for polymorphic models supporting multiple resource types.
    
    Handles models that represent different types of resources
    (e.g., Animal model with Cat and Dog subtypes).
    """
    
    def to_representation(self, instance):
        """
        Convert instance to representation with correct resource type.
        
        Args:
            instance: Polymorphic model instance
            
        Returns:
            dict: Resource object with appropriate type
        """
    
    def get_polymorphic_types(self):
        """
        Get list of possible resource types for this serializer.
        
        Returns:
            list: Available resource type names
        """

Field Name Formatting

All serializers support automatic field name formatting controlled by settings:

# settings.py
JSON_API_FORMAT_FIELD_NAMES = True  # Convert snake_case to kebab-case

# Model field: created_at -> JSON:API attribute: "created-at"
# Model field: author_id -> JSON:API attribute: "author-id"

Error Handling

Serializers integrate with JSON:API error formatting:

# Validation errors are automatically formatted as JSON:API errors:
# {
#   "errors": [{
#     "detail": "This field is required.",
#     "source": {"pointer": "/data/attributes/title"},
#     "status": "400"
#   }]
# }

Relationship Handling

Serializers automatically detect and handle relationships:

  • ForeignKey fields become to-one relationships
  • ManyToMany and reverse ForeignKey fields become to-many relationships
  • Related fields are moved to relationships section
  • Resource identifier objects are generated for relationship data

Types

# All Django REST framework serializer types are available
# Plus JSON:API specific classes above

from rest_framework.serializers import *  # All DRF serializers re-exported
from rest_framework_json_api.serializers import (
    ModelSerializer,
    HyperlinkedModelSerializer,
    ResourceIdentifierObjectSerializer,
    SparseFieldsetsMixin,
    PolymorphicModelSerializer
)

Install with Tessl CLI

npx tessl i tessl/pypi-djangorestframework-jsonapi

docs

exceptions-utilities.md

filtering.md

index.md

pagination.md

relations.md

renderers-parsers.md

serializers.md

views.md

tile.json