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,
    ModelSchema,
    JSONAPIRenderer,
    QueryStringManager,
    HTTPException,
    BadRequest,
    NotFound,
    apply_attributes,
    get_rel_id,
    get_rel_ids,
    jsonapi_paginate,
    jsonapi_pagination,
    jsonapi_cursor_pagination,
    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.9.0.tar.gz (31.1 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.9.0-py3-none-any.whl (40.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: django_ninja_jsonapi-0.9.0.tar.gz
  • Upload date:
  • Size: 31.1 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.9.0.tar.gz
Algorithm Hash digest
SHA256 6bcecc8272cec5311d1117a4d64d3ff1fa9fd6d2265b2d7a3d343cd8de8b68f8
MD5 f4c5ac2c0c6daef8e4c5014ad16176d6
BLAKE2b-256 3b6c5759937cfa4e02831813eae44780e1e03c0dd8795623e40b109e2fdc1884

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for django_ninja_jsonapi-0.9.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f09495013842f6438a5d8ea779a0114e4779c5a7f761608b63745fcf1ae19ea2
MD5 1aee4256d59cfa43d48e7d8608b52fb5
BLAKE2b-256 b5ea3fb8f511a9bc953517da72b86d4c7c3ee0d5f240efe8ae3fd0e6b95956fd

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