Skip to main content

JSON:API toolkit for Django Ninja

Project description

django-ninja-jsonapi

JSON:API toolkit for Django Ninja.

CI Package codecov PyPI Python Versions Django Versions PyPI Monthly Downloads Ruff ty uv

This project brings JSON:API specification support to Django Ninja.

Full documentation is available at ignacemaes.com/django-ninja-jsonapi.

Status

  • Transparent JSON:API wrapping — write plain Django Ninja views, get JSON:API documents automatically.
  • Auto-detected relationships from Pydantic schema type hints.
  • Strict query parsing for JSON:API-style filter, sort, include, fields, and page parameters.
  • JSON:API exception payload handling.
  • Content-type negotiation (415/406) per the JSON:API spec.
  • Attribute key inflection (dasherize or camelize).

Requirements

  • Python 3.10+
  • Django 4.2+
  • Django Ninja 1.0+

Install

uv add django-ninja-jsonapi

or

  • pip install django-ninja-jsonapi
  • poetry add django-ninja-jsonapi
  • pdm add django-ninja-jsonapi

Quick start

1) Define a Django model and schemas

from typing import ClassVar

from django.db import models
from pydantic import BaseModel

from django_ninja_jsonapi import JsonApiMeta


class Customer(models.Model):
    name = models.CharField(max_length=128)


class CustomerSchema(BaseModel):
    id: int
    name: str

    jsonapi_meta: ClassVar[JsonApiMeta] = JsonApiMeta(resource_type="customers")


class CustomerCreateSchema(BaseModel):
    name: str

2) Create your API with NinjaJsonAPI

from django_ninja_jsonapi import NinjaJsonAPI

api = NinjaJsonAPI()


@api.get("/customers", response=list[CustomerSchema])
def list_customers(request):
    return Customer.objects.all()


@api.get("/customers/{customer_id}", response=CustomerSchema)
def get_customer(request, customer_id: int):
    return Customer.objects.get(pk=customer_id)


@api.post("/customers", response={201: CustomerSchema})
def create_customer(request, body: CustomerCreateSchema):
    customer = Customer.objects.create(**body.model_dump())
    return 201, customer

3) Mount API in Django URLs

from django.urls import path
from .api import api

urlpatterns = [
    path("api/", api.urls),
]

Example response

GET /api/customers/1

{
  "data": {
    "type": "customers",
    "id": "1",
    "attributes": {
      "name": "Alice"
    }
  }
}

GET /api/customers

{
  "data": [
    {
      "type": "customers",
      "id": "1",
      "attributes": { "name": "Alice" }
    },
    {
      "type": "customers",
      "id": "2",
      "attributes": { "name": "Bob" }
    }
  ]
}

Resources have a type and id at the top level while model fields are nested under attributes. Relationships, includes, sparse fieldsets, filtering, sorting and pagination all follow the JSON:API specification.

Architecture

NinjaJsonAPI is a NinjaAPI subclass that transparently wraps responses in JSON:API documents and unwraps JSON:API request bodies into plain Pydantic schemas.

flowchart LR
    Client -->|HTTP request| NinjaJsonAPI
    NinjaJsonAPI --> ContentNegotiation["Content Negotiation\n(415 / 406)"]
    ContentNegotiation --> Unwrap["Unwrap JSON:API body\n→ plain Pydantic schema"]
    Unwrap --> Endpoint["Your endpoint\n(plain Django Ninja view)"]
    Endpoint -->|"dict / Pydantic / QuerySet"| JSONAPIRenderer
    JSONAPIRenderer -->|"application/vnd.api+json"| Client

Configuration

Set JSON:API options in Django settings:

NINJA_JSONAPI = {
    "MAX_INCLUDE_DEPTH": 3,
    "MAX_PAGE_SIZE": 20,
    "ALLOW_DISABLE_PAGINATION": True,
    "INCLUDE_JSONAPI_OBJECT": False,
    "JSONAPI_VERSION": "1.0",
    "INFLECTION": "dasherize",  # or "camelize", or None (default)
}

Exported public API

from django_ninja_jsonapi import (
    NinjaJsonAPI,
    JsonApiMeta,
    JSONAPIRenderer,
    QueryStringManager,
    HTTPException,
    BadRequest,
    NotFound,
    apply_attributes,
    get_rel_id,
    get_rel_ids,
    model_schema,
    jsonapi_paginate,
    jsonapi_include,
    jsonapi_meta,
    jsonapi_links,
    jsonapi_sort,
    jsonapi_filter,
    parse_include,
)

Contributing

See CONTRIBUTING.md for setup, local checks, contribution workflow, and maintainer release notes.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_ninja_jsonapi-0.8.0.tar.gz (30.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_ninja_jsonapi-0.8.0-py3-none-any.whl (39.4 kB view details)

Uploaded Python 3

File details

Details for the file django_ninja_jsonapi-0.8.0.tar.gz.

File metadata

  • Download URL: django_ninja_jsonapi-0.8.0.tar.gz
  • Upload date:
  • Size: 30.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for django_ninja_jsonapi-0.8.0.tar.gz
Algorithm Hash digest
SHA256 b3877c381434b46705653735663e38ae372a63fb434843bb9352b0a656c79b0b
MD5 127212311531ad49aed4897d543b7a66
BLAKE2b-256 b70a585cfc793d5e569392a00f7a89ec044a25c0af44ec5e68a1f88b93e903af

See more details on using hashes here.

File details

Details for the file django_ninja_jsonapi-0.8.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_ninja_jsonapi-0.8.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a3b60e4fa55d88b43afc9481b253d245e6861fe9aa821688ba0690f4cdc3de6e
MD5 04154891d81de381df42d012616546df
BLAKE2b-256 bdc45c23b665b922edefe89a6dbe1c0350739ce18c5b54f4aa99946291629e08

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page