NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI
PyPI, #1883 most downloaded on PyPI
Django Ninja - Fast Django REST framework
Latest stable
1.8.0
Last release 14 days ago
08 Nov 2026
Release timing varies
gaps range from 1 weeks to 5 months
Nearly every release is documented
notes for 54 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
7 years old
91 releases · first in 2019
Drag across the ruler to compare, or tap a release to open it.
Add SECURITY.md with private vulnerability reporting instructions by @vitalik in https://github.com/vitalik/django-ninja/commit/3506fd47cca7f30e2a65b4…
You can now document the webhooks your API sends. Decorate the payload Schema with @api.webhook or @router.webhook and it appears in the OpenAPI 3.1 `webh## What's New
You can now document the webhooks your API sends. Decorate the payload Schema with @api.webhook or @router.webhook and it appears in the OpenAPI 3.1 webhooks section, so Swagger and Redoc show it next to your operations. This is documentation only: Ninja doesn't send anything. The guide shows one way to deliver them with Django tasks.
from ninja import NinjaAPI, Router, Schema
api = NinjaAPI()
@api.webhook("order.paid")
class OrderPaid(Schema):
id: int
total: Decimal
router = Router(tags=["orders"])
@router.webhook # name defaults to the class name: "OrderShipped"
class OrderShipped(Schema):
id: int
The docs at django-ninja.dev are reorganized into four sections:
The docs now include files for LLMs. Point your coding assistant at /llms.txt, which has usage notes and a link to every page, or at /llms-full.txt, which is the whole Guide in one file. Every page is also served as raw Markdown, e.g. /guide/routers.md.
register_field() accepts field classesA custom Django field that subclasses a built-in one inherits its internal type, so registering it by name ("UUIDField") would change every UUIDField. You can now register the field class itself:
from typing import Annotated
from pydantic import BeforeValidator
from ninja.orm import register_field
class PublicIDField(models.UUIDField):
def from_db_value(self, value, expression, connection):
return PublicID(value)
register_field(PublicIDField, Annotated[str, BeforeValidator(str)])
The registration also applies to subclasses, and the most specific class wins. It also covers ForeignKey and OneToOne fields that point at that field. Forward FK and OneToOne fields now take their type from the to_field target instead of always using the related model's pk.
An Optional schema used as a Query, Header or Form param now falls back to its default when none of its fields are sent:
class Filters(Schema):
city: str
year: int = 2026
@api.get("/events")
def events(request, filters: Filters | None = Query(None)):
...
# GET /events -> filters is None (was 422)
# GET /events?city=Kyiv -> Filters(city="Kyiv", year=2026)
Body params next to filesWhen you mix Body params with File or Form, each multipart part is now read the way Swagger and generated clients send it. Primitive types (str, int, date, Enum, EmailStr, ...) are read as plain text, and objects and arrays are read as JSON:
@api.post("/upload")
def upload(
request,
file: File[UploadedFile],
note: str = Body(...),
day: date = Body(...),
meta: dict[str, int] | None = Body(None),
):
...
# note='say "hi"' day=2024-01-02 meta='{"a": 1}' -> 200 (quoted strings and dates used to give 400)
Model fields now always come first, in model order, followed by your custom fields. A field you declare on the schema is used as-is, so a third-party model field that Ninja can't convert no longer breaks fields = "__all__":
class ProductOut(ModelSchema):
price: str # MoneyField: no register_field() needed when declared
tags: list[str] = []
class Meta:
model = Product
fields = "__all__"
list(ProductOut.model_fields) # ['id', 'name', 'price', 'tags']
Listing a FK by its attname (user_id) in Meta.fields now gives an error that suggests the fix: use user, or declare user_id: int.
Django Ninja is now tested on Python 3.15 with Django 5.2, 6.0 and 6.1.
NINJA_PAGINATION_MAX_OFFSET setting is removed, and a value left in settings is ignored (#1818)ForeignKey(..., to_field="slug") is now typed from the target field (string) instead of the related pk (integer). If a string to_field holds numeric values, responses now return "123" instead of 123 (#1842)Meta.fields order) before custom fields. This changes the key order in responses and in OpenAPI (#1829)Meta.fields now emits a DeprecationWarning. It will become a ConfigError in a later release (#1815)depth > 0 are now Optional in the schema (anyOf: [..., null]) (#1803)Union/Annotated items get their own schema names (PagedFooOrBar instead of a shared PagedUnion or PagedAnnotated). Models in generated clients may be renamed (#1800)str Body part sent with literal surrounding quotes now keeps them (#1825)@api.webhook / @router.webhook for OpenAPI 3.1 webhooks by @vitalik in https://github.com/vitalik/django-ninja/pull/1783register_field() accepts field classes; FK/O2O typed from to_field target by @vitalik in https://github.com/vitalik/django-ninja/pull/1842Meta.fields by @smoltafet in https://github.com/vitalik/django-ninja/pull/1815user_id) in Meta.fields by @vitalik in https://github.com/vitalik/django-ninja/pull/1832depth > 0 by @moneebullah25 in https://github.com/vitalik/django-ninja/pull/1803base_class in the ModelSchema factory cache key by @moneebullah25 in https://github.com/vitalik/django-ninja/pull/1804create_schema crash on models with a ForeignObject reverse relation by @shivanij1203 in https://github.com/vitalik/django-ninja/pull/1746Body parts by their schema: primitives as plain text, objects and arrays as JSON, by @vitalik in https://github.com/vitalik/django-ninja/pull/1825 and https://github.com/vitalik/django-ninja/pull/1850alias="0") nulling out fields on object input by @smoltafet in https://github.com/vitalik/django-ninja/pull/1817exclude_unset for nested Schema instances, while nested instances are still re-validated by @vitalik in https://github.com/vitalik/django-ninja/pull/1830 and https://github.com/vitalik/django-ninja/pull/1846CursorPagination returning 500 for malformed cursors by @moneebullah25 in https://github.com/vitalik/django-ninja/pull/1794CursorPagination 500 on tie runs of 100+ rows by @vitalik in https://github.com/vitalik/django-ninja/pull/1818i.get is not a function crash) by @vitalik in https://github.com/vitalik/django-ninja/pull/1844Callable and Dict annotations on operations and the test client by @NorthIsUp in https://github.com/vitalik/django-ninja/pull/1789llms.txt, llms-full.txt) by @Nuung in https://github.com/vitalik/django-ninja/pull/1799typing.List/Dict/Optional in favor of builtin generics by @vitalik in https://github.com/vitalik/django-ninja/pull/1782Status from single-response Quick Start examples by @vitalik in https://github.com/vitalik/django-ninja/pull/1790constant_time_compare in auth examples by @Highdrien in https://github.com/vitalik/django-ninja/pull/1781request.auth with VIEW-mode decorators by @vitalik in https://github.com/vitalik/django-ninja/pull/1831test_all_fields on pydantic 2.14 by @vitalik in https://github.com/vitalik/django-ninja/pull/1797SECURITY.md with private vulnerability reporting instructions by @vitalik in https://github.com/vitalik/django-ninja/commit/3506fd47cca7f30e2a65b49833798ba18c8d7b9dFull Changelog: https://github.com/vitalik/django-ninja/compare/v1.7.1...v1.8.0b1 ooks` section, so Swagger and Redoc show it next to your operations. This is documentation only: Ninja doesn't send anything. The guide shows one way to deliver them with Django tasks.
from ninja import NinjaAPI, Router, Schema
api = NinjaAPI()
@api.webhook("order.paid")
class OrderPaid(Schema):
id: int
total: Decimal
router = Router(tags=["orders"])
@router.webhook # name defaults to the class name: "OrderShipped"
class OrderShipped(Schema):
id: int
The docs at django-ninja.dev are reorganized into four sections:
The docs now include files for LLMs. Point your coding assistant at /llms.txt, which has usage notes and a link to every page, or at /llms-full.txt, which is the whole Guide in one file. Every page is also served as raw Markdown, e.g. /guide/routers.md.
register_field() accepts field classesA custom Django field that subclasses a built-in one inherits its internal type, so registering it by name ("UUIDField") would change every UUIDField. You can now register the field class itself:
from typing import Annotated
from pydantic import BeforeValidator
from ninja.orm import register_field
class PublicIDField(models.UUIDField):
def from_db_value(self, value, expression, connection):
return PublicID(value)
register_field(PublicIDField, Annotated[str, BeforeValidator(str)])
The registration also applies to subclasses, and the most specific class wins. It also covers ForeignKey and OneToOne fields that point at that field. Forward FK and OneToOne fields now take their type from the to_field target instead of always using the related model's pk.
An Optional schema used as a Query, Header or Form param now falls back to its default when none of its fields are sent:
class Filters(Schema):
city: str
year: int = 2026
@api.get("/events")
def events(request, filters: Filters | None = Query(None)):
...
# GET /events -> filters is None (was 422)
# GET /events?city=Kyiv -> Filters(city="Kyiv", year=2026)
Body params next to filesWhen you mix Body params with File or Form, each multipart part is now read the way Swagger and generated clients send it. Primitive types (str, int, date, Enum, EmailStr, ...) are read as plain text, and objects and arrays are read as JSON:
@api.post("/upload")
def upload(
request,
file: File[UploadedFile],
note: str = Body(...),
day: date = Body(...),
meta: dict[str, int] | None = Body(None),
):
...
# note='say "hi"' day=2024-01-02 meta='{"a": 1}' -> 200 (quoted strings and dates used to give 400)
Model fields now always come first, in model order, followed by your custom fields. A field you declare on the schema is used as-is, so a third-party model field that Ninja can't convert no longer breaks fields = "__all__":
class ProductOut(ModelSchema):
price: str # MoneyField: no register_field() needed when declared
tags: list[str] = []
class Meta:
model = Product
fields = "__all__"
list(ProductOut.model_fields) # ['id', 'name', 'price', 'tags']
Listing a FK by its attname (user_id) in Meta.fields now gives an error that suggests the fix: use user, or declare user_id: int.
Django Ninja is now tested on Python 3.15 with Django 5.2, 6.0 and 6.1.
NINJA_PAGINATION_MAX_OFFSET setting is removed, and a value left in settings is ignored (#1818)ForeignKey(..., to_field="slug") is now typed from the target field (string) instead of the related pk (integer). If a string to_field holds numeric values, responses now return "123" instead of 123 (#1842)Meta.fields order) before custom fields. This changes the key order in responses and in OpenAPI (#1829)Meta.fields now emits a DeprecationWarning. It will become a ConfigError in a later release (#1815)depth > 0 are now Optional in the schema (anyOf: [..., null]) (#1803)Union/Annotated items get their own schema names (PagedFooOrBar instead of a shared PagedUnion or PagedAnnotated). Models in generated clients may be renamed (#1800)str Body part sent with literal surrounding quotes now keeps them (#1825)@api.webhook / @router.webhook for OpenAPI 3.1 webhooks by @vitalik in https://github.com/vitalik/django-ninja/pull/1783register_field() accepts field classes; FK/O2O typed from to_field target by @vitalik in https://github.com/vitalik/django-ninja/pull/1842Meta.fields by @smoltafet in https://github.com/vitalik/django-ninja/pull/1815user_id) in Meta.fields by @vitalik in https://github.com/vitalik/django-ninja/pull/1832depth > 0 by @moneebullah25 in https://github.com/vitalik/django-ninja/pull/1803base_class in the ModelSchema factory cache key by @moneebullah25 in https://github.com/vitalik/django-ninja/pull/1804create_schema crash on models with a ForeignObject reverse relation by @shivanij1203 in https://github.com/vitalik/django-ninja/pull/1746Body parts by their schema: primitives as plain text, objects and arrays as JSON, by @vitalik in https://github.com/vitalik/django-ninja/pull/1825 and https://github.com/vitalik/django-ninja/pull/1850alias="0") nulling out fields on object input by @smoltafet in https://github.com/vitalik/django-ninja/pull/1817exclude_unset for nested Schema instances, while nested instances are still re-validated by @vitalik in https://github.com/vitalik/django-ninja/pull/1830 and https://github.com/vitalik/django-ninja/pull/1846CursorPagination returning 500 for malformed cursors by @moneebullah25 in https://github.com/vitalik/django-ninja/pull/1794CursorPagination 500 on tie runs of 100+ rows by @vitalik in https://github.com/vitalik/django-ninja/pull/1818i.get is not a function crash) by @vitalik in https://github.com/vitalik/django-ninja/pull/1844Callable and Dict annotations on operations and the test client by @NorthIsUp in https://github.com/vitalik/django-ninja/pull/1789llms.txt, llms-full.txt) by @Nuung in https://github.com/vitalik/django-ninja/pull/1799typing.List/Dict/Optional in favor of builtin generics by @vitalik in https://github.com/vitalik/django-ninja/pull/1782Status from single-response Quick Start examples by @vitalik in https://github.com/vitalik/django-ninja/pull/1790constant_time_compare in auth examples by @Highdrien in https://github.com/vitalik/django-ninja/pull/1781request.auth with VIEW-mode decorators by @vitalik in https://github.com/vitalik/django-ninja/pull/1831test_all_fields on pydantic 2.14 by @vitalik in https://github.com/vitalik/django-ninja/pull/1797SECURITY.md with private vulnerability reporting instructions by @vitalik in https://github.com/vitalik/django-ninja/commit/3506fd47cca7f30e2a65b49833798ba18c8d7b9dFull Changelog: https://github.com/vitalik/django-ninja/compare/v1.7.1...v1.8.0b1
Your coding agent can read these notes before it upgrades. Set up the MCP server →
Add SECURITY.md with private vulnerability reporting instructions by @vitalik in 3506fd4
You can now document the webhooks your API sends. Decorate the payload Schema with @api.webhook or @router.webhook and it appears in the OpenAPI 3.1 webhooks section, so Swagger and Redoc show it next to your operations. This is documentation only: Ninja doesn't send anything. The guide shows one way to deliver them with Django tasks.
from ninja import NinjaAPI, Router, Schema
api = NinjaAPI()
@api.webhook("order.paid")
class OrderPaid(Schema):
id: int
total: Decimal
router = Router(tags=["orders"])
@router.webhook # name defaults to the class name: "OrderShipped"
class OrderShipped(Schema):
id: intThe docs at django-ninja.dev are reorganized into four sections:
The docs now include files for LLMs. Point your coding assistant at /llms.txt, which has usage notes and a link to every page, or at /llms-full.txt, which is the whole Guide in one file. Every page is also served as raw Markdown, e.g. /guide/routers.md.
register_field() accepts field classesA custom Django field that subclasses a built-in one inherits its internal type, so registering it by name ("UUIDField") would change every UUIDField. You can now register the field class itself:
from typing import Annotated
from pydantic import BeforeValidator
from ninja.orm import register_field
class PublicIDField(models.UUIDField):
def from_db_value(self, value, expression, connection):
return PublicID(value)
register_field(PublicIDField, Annotated[str, BeforeValidator(str)])The registration also applies to subclasses, and the most specific class wins. It also covers ForeignKey and OneToOne fields that point at that field. Forward FK and OneToOne fields now take their type from the to_field target instead of always using the related model's pk.
An Optional schema used as a Query, Header or Form param now falls back to its default when none of its fields are sent:
class Filters(Schema):
city: str
year: int = 2026
@api.get("/events")
def events(request, filters: Filters | None = Query(None)):
...
# GET /events -> filters is None (was 422)
# GET /events?city=Kyiv -> Filters(city="Kyiv", year=2026)Body params next to filesWhen you mix Body params with File or Form, each multipart part is now read the way Swagger and generated clients send it. Primitive types (str, int, date, Enum, EmailStr, ...) are read as plain text, and objects and arrays are read as JSON:
@api.post("/upload")
def upload(
request,
file: File[UploadedFile],
note: str = Body(...),
day: date = Body(...),
meta: dict[str, int] | None = Body(None),
):
...
# note='say "hi"' day=2024-01-02 meta='{"a": 1}' -> 200 (quoted strings and dates used to give 400)Model fields now always come first, in model order, followed by your custom fields. A field you declare on the schema is used as-is, so a third-party model field that Ninja can't convert no longer breaks fields = "__all__":
class ProductOut(ModelSchema):
price: str # MoneyField: no register_field() needed when declared
tags: list[str] = []
class Meta:
model = Product
fields = "__all__"
list(ProductOut.model_fields) # ['id', 'name', 'price', 'tags']Listing a FK by its attname (user_id) in Meta.fields now gives an error that suggests the fix: use user, or declare user_id: int.
Django Ninja is now tested on Python 3.15 with Django 5.2, 6.0 and 6.1.
NINJA_PAGINATION_MAX_OFFSET setting is removed, and a value left in settings is ignored (#1818)ForeignKey(..., to_field="slug") is now typed from the target field (string) instead of the related pk (integer). If a string to_field holds numeric values, responses now return "123" instead of 123 (#1842)Meta.fields order) before custom fields. This changes the key order in responses and in OpenAPI (#1829)Meta.fields now emits a DeprecationWarning. It will become a ConfigError in a later release (#1815)depth > 0 are now Optional in the schema (anyOf: [..., null]) (#1803)Union/Annotated items get their own schema names (PagedFooOrBar instead of a shared PagedUnion or PagedAnnotated). Models in generated clients may be renamed (#1800)str Body part sent with literal surrounding quotes now keeps them (#1825)@api.webhook / @router.webhook for OpenAPI 3.1 webhooks by @vitalik in #1783register_field() accepts field classes; FK/O2O typed from to_field target by @vitalik in #1842Meta.fields by @smoltafet in #1815user_id) in Meta.fields by @vitalik in #1832depth > 0 by @moneebullah25 in #1803base_class in the ModelSchema factory cache key by @moneebullah25 in #1804create_schema crash on models with a ForeignObject reverse relation by @shivanij1203 in #1746Body parts by their schema: primitives as plain text, objects and arrays as JSON, by @vitalik in #1825 and #1850alias="0") nulling out fields on object input by @smoltafet in #1817exclude_unset for nested Schema instances, while nested instances are still re-validated by @vitalik in #1830 and #1846CursorPagination returning 500 for malformed cursors by @moneebullah25 in #1794CursorPagination 500 on tie runs of 100+ rows by @vitalik in #1818i.get is not a function crash) by @vitalik in #1844Callable and Dict annotations on operations and the test client by @NorthIsUp in #1789llms.txt, llms-full.txt) by @Nuung in #1799typing.List/Dict/Optional in favor of builtin generics by @vitalik in #1782Status from single-response Quick Start examples by @vitalik in #1790constant_time_compare in auth examples by @Highdrien in #1781request.auth with VIEW-mode decorators by @vitalik in #1831test_all_fields on pydantic 2.14 by @vitalik in #1797SECURITY.md with private vulnerability reporting instructions by @vitalik in 3506fd4Full Changelog: v1.7.1...v1.8.0b1
Filter the response by the declared schema when a view returns a subclass instance in https://github.com/vitalik/django-ninja/pull/1823
response=UserOut and returned an instance of a subclass of UserOut, fields defined only on the subclass were included in the response (since 1.6.0). Now only the declared schema's fields are returned, as in 1.5.x.Annotated[...] response types (e.g. with PlainSerializer) are now applied when a model instance is returned.If your views return instances of subclasses of their response schema, we recommend upgrading.
Hotfix release cut from v1.7.2. It contains only the changes above.
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.7.2...v1.7.3
Fix auth/throttle overrides for nested routers in #1820
api.add_router(..., auth=..., throttle=...) now also applies to routers nested inside the mounted routerRouter.add_router(..., auth=..., throttle=...) keeps the override per mount, so a child router reused under several parents gets the right settings under each oneIf you use nested routers with auth or throttle set on add_router(), we recommend upgrading.
Security reviewer reference: ANT-2026-H81LRF3W
Hotfix release cut from v1.7.1. It contains only the changes above (plus a test-only fix for pydantic 2.14, #1797).
Full Changelog: v1.7.1...v1.7.2
fix(auth): preserve percent sequences in HTTP Basic credentials by @Aryan-coder-student in #1780
fix(auth): preserve percent sequences in HTTP Basic credentials by @Aryan-coder-student in #1780
fix: avoid duplicate async authentication calls by @tunglambk in #1755
Migrate from flit to uv for CI/CD, contributing and publishing by @vitalik in #1770
docs: add authorization and permissions section by @namelessweakl1ng in #1744
docs: add decorator example to permissions section by @vitalik in #1776
Full Changelog: v1.7.0...v1.7.1
fix(auth): preserve percent sequences in HTTP Basic credentials by @Aryan-coder-student in https://github.com/vitalik/django-ninja/pull/1780
fix: avoid duplicate async authentication calls by @tunglambk in https://github.com/vitalik/django-ninja/pull/1755
Migrate from flit to uv for CI/CD, contributing and publishing by @vitalik in https://github.com/vitalik/django-ninja/pull/1770
docs: add authorization and permissions section by @namelessweakl1ng in https://github.com/vitalik/django-ninja/pull/1744
docs: add decorator example to permissions section by @vitalik in https://github.com/vitalik/django-ninja/pull/1776
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.7.0...v1.7.1
Pre-release exercising PyPI Trusted Publishing (OIDC) via uv ( #1771 ). No functional changes since 1.7.1a1.
Pre-release exercising PyPI Trusted Publishing (OIDC) via uv (#1771). No functional changes since 1.7.1a1.
Pre-release exercising the new uv-based CI/CD and publishing pipeline ( #1770 ).
Pre-release exercising the new uv-based CI/CD and publishing pipeline (#1770).
No functional changes since 1.7.0 — tooling migration only: flit → uv for contributing, CI, and publishing (build backend remains flit_core).
LimitOffsetPagination to support max_limit in decorator by @vitalik in #1709
Full Changelog: v1.6.2...v1.7.0b1
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.6.2...v1.7.0
LimitOffsetPagination to support max_limit in decorator by @vitalik in https://github.com/vitalik/django-ninja/pull/1709
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.6.2...v1.7.0b1
Filter the response by the declared schema when a view returns a subclass instance in https://github.com/vitalik/django-ninja/pull/1822
response=UserOut and returned an instance of a subclass of UserOut, fields defined only on the subclass were included in the response (since 1.6.0). Now only the declared schema's fields are returned, as in 1.5.x.Annotated[...] response types (e.g. with PlainSerializer) are now applied when a model instance is returned.If your views return instances of subclasses of their response schema, we recommend upgrading.
Hotfix release cut from v1.6.4. It contains only the changes above.
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.6.4...v1.6.5
Fix auth/throttle overrides for nested routers in #1819
api.add_router(..., auth=..., throttle=...) now also applies to routers nested inside the mounted routerRouter.add_router(..., auth=..., throttle=...) keeps the override per mount, so a child router reused under several parents gets the right settings under each oneIf you use nested routers with auth or throttle set on add_router(), we recommend upgrading.
Security reviewer reference: ANT-2026-H81LRF3W
Hotfix release cut from v1.6.3. It contains only the changes above (plus a test-only fix for pydantic 2.14, #1797).
Full Changelog: v1.6.3...v1.6.4
Drop Django upper version constraint by @Stormheg in https://github.com/vitalik/django-ninja/pull/1749
Hotfix release cut from v1.6.2 — contains only the changes above, none of the other work currently on master.
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.6.2...v1.6.3
Hotfix release cut from v1.6.2 — contains only the changes above, none of the other work currently on master.
Full Changelog: v1.6.2...v1.6.3
allow "app_label.ModelName" format for ModelSchema model by @andreasnuesslein in https://github.com/vitalik/django-ninja/pull/1590
"app_label.ModelName" format for ModelSchema model by @andreasnuesslein in https://github.com/vitalik/django-ninja/pull/1590Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.6.1...v1.6.2
"app_label.ModelName" format for ModelSchema model by @andreasnuesslein in #1590Full Changelog: v1.6.1...v1.6.2
Make Status generic by @vitalik in https://github.com/vitalik/django-ninja/pull/1694
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.6.0...v1.6.1
Full Changelog: v1.6.0...v1.6.1
New Status class for explicitly returning HTTP status codes. Replaces the old tuple syntax (status_code, body) which is now deprecated.
Routers are now reusable and can be mounted to multiple APIs or multiple times within the same API. Decorators, auth, tags, and throttle settings are fully isolated between mounts.
router = Router(tags=["shared"])
@router.get("/items")
def list_items(request):
return [{"id": 1}]
# Mount same router to multiple APIs
api_v1 = NinjaAPI(urls_namespace="v1")
api_v1.add_router("/", router)
api_v2 = NinjaAPI(urls_namespace="v2")
api_v2.add_router("/", router) # !!! Before this was giving an error
New CursorPagination class for stable pagination over frequently changing datasets. Uses base64-encoded cursor tokens instead of offsets, ensuring consistent results even when items are added or removed.
from ninja.pagination import paginate, CursorPagination
@api.get("/events", response=list[EventSchema])
@paginate(CursorPagination, ordering=("-created",), page_size=20)
def list_events(request):
return Event.objects.all()
New Status class for explicitly returning HTTP status codes. Replaces the old tuple syntax (status_code, body) which is now deprecated.
from ninja import Status
@api.post("/login", response={200: Token, 401: Message})
def login(request, payload: Auth):
if not valid:
return Status(401, {"message": "Unauthorized"})
return Status(200, {"token": token})
When returning a Pydantic model instance that already matches the response schema, Django Ninja now skips redundant validation and directly serializes — a nice performance boost.
@api.get("/user", response=UserOut)
def get_user(request):
return UserOut(id=1, name="John") # skips re-validation
First-class streaming support with automatic schema validation for each chunk. Supports both JSONL and Server-Sent Events formats.
from ninja.streaming import JSONL, SSE
@api.get("/items", response=JSONL[Item])
def stream_items(request):
for i in range(100):
yield {"name": f"item-{i}", "price": float(i)}
@api.get("/events", response=SSE[Item])
async def stream_events(request):
async for item in get_items():
yield item
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.5.3...v1.6.0
Routers are now reusable and can be mounted to multiple APIs or multiple times within the same API. Decorators, auth, tags, and throttle settings are fully isolated between mounts.
router = Router(tags=["shared"])
@router.get("/items")
def list_items(request):
return [{"id": 1}]
# Mount same router to multiple APIs
api_v1 = NinjaAPI(urls_namespace="v1")
api_v1.add_router("/", router)
api_v2 = NinjaAPI(urls_namespace="v2")
api_v2.add_router("/", router) # !!! Before this was giving an errorNew CursorPagination class for stable pagination over frequently changing datasets. Uses base64-encoded cursor tokens instead of offsets, ensuring consistent results even when items are added or removed.
from ninja.pagination import paginate, CursorPagination
@api.get("/events", response=list[EventSchema])
@paginate(CursorPagination, ordering=("-created",), page_size=20)
def list_events(request):
return Event.objects.all()New Status class for explicitly returning HTTP status codes. Replaces the old tuple syntax (status_code, body) which is now deprecated.
from ninja import Status
@api.post("/login", response={200: Token, 401: Message})
def login(request, payload: Auth):
if not valid:
return Status(401, {"message": "Unauthorized"})
return Status(200, {"token": token})When returning a Pydantic model instance that already matches the response schema, Django Ninja now skips redundant validation and directly serializes — a nice performance boost.
@api.get("/user", response=UserOut)
def get_user(request):
return UserOut(id=1, name="John") # skips re-validationFirst-class streaming support with automatic schema validation for each chunk. Supports both JSONL and Server-Sent Events formats.
from ninja.streaming import JSONL, SSE
@api.get("/items", response=JSONL[Item])
def stream_items(request):
for i in range(100):
yield {"name": f"item-{i}", "price": float(i)}
@api.get("/events", response=SSE[Item])
async def stream_events(request):
async for item in get_items():
yield itemFull Changelog: v1.5.3...v1.6.0
New Status class for explicitly returning HTTP status codes. Replaces the old tuple syntax (status_code, body) which is now deprecated.
Note: This is beta release which is still testing - we encorage you to test this release as well and provide feedback
Routers are now reusable and can be mounted to multiple APIs or multiple times within the same API. Decorators, auth, tags, and throttle settings are fully isolated between mounts.
router = Router(tags=["shared"])
@router.get("/items")
def list_items(request):
return [{"id": 1}]
# Mount same router to multiple APIs
api_v1 = NinjaAPI(urls_namespace="v1")
api_v1.add_router("/", router)
api_v2 = NinjaAPI(urls_namespace="v2")
api_v2.add_router("/", router) # !!! Before this was giving an error
New CursorPagination class for stable pagination over frequently changing datasets. Uses base64-encoded cursor tokens instead of offsets, ensuring consistent results even when items are added or removed.
from ninja.pagination import paginate, CursorPagination
@api.get("/events", response=list[EventSchema])
@paginate(CursorPagination, ordering=("-created",), page_size=20)
def list_events(request):
return Event.objects.all()
New Status class for explicitly returning HTTP status codes. Replaces the old tuple syntax (status_code, body) which is now deprecated.
from ninja import Status
@api.post("/login", response={200: Token, 401: Message})
def login(request, payload: Auth):
if not valid:
return Status(401, {"message": "Unauthorized"})
return Status(200, {"token": token})
When returning a Pydantic model instance that already matches the response schema, Django Ninja now skips redundant validation and directly serializes — a nice performance boost.
@api.get("/user", response=UserOut)
def get_user(request):
return UserOut(id=1, name="John") # skips re-validation
First-class streaming support with automatic schema validation for each chunk. Supports both JSONL and Server-Sent Events formats.
from ninja.streaming import JSONL, SSE
@api.get("/items", response=JSONL[Item])
def stream_items(request):
for i in range(100):
yield {"name": f"item-{i}", "price": float(i)}
@api.get("/events", response=SSE[Item])
async def stream_events(request):
async for item in get_items():
yield item
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.5.3...v1.6.0b1
Fixed swagger css #1648
Fixed swagger css #1648
Updated JS bundles to latest versions
A minor update
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.5.1...v1.5.2
Add dark mode favicons and template to overwrite favicons by @dpgraham4401 in https://github.com/vitalik/django-ninja/pull/1587
Misc
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.5.0...v1.5.1
Misc
Full Changelog: v1.5.0...v1.5.1
Remove Deprecated Config class support by @vitalik in https://github.com/vitalik/django-ninja/pull/1528
^+ Fix issues with nested default dicts by @HeyHugo in https://github.com/vitalik/django-ninja/pull/1582PathEx with Annotated types by @jceipek in https://github.com/vitalik/django-ninja/pull/1574Chances since Beta1 Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.5.0b1...v1.5.0b2
^+ Fix issues with nested default dicts by @HeyHugo in #1582PathEx with Annotated types by @jceipek in #1574Chances since Beta1
Full Changelog: v1.5.0b1...v1.5.0b2
Remove Deprecated Config class support by @vitalik in https://github.com/vitalik/django-ninja/pull/1528
^+ Fix issues with nested default dicts by @HeyHugo in https://github.com/vitalik/django-ninja/pull/1582PathEx with Annotated types by @jceipek in https://github.com/vitalik/django-ninja/pull/1574Chances since Beta1 Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.5.0b1...v1.5.0b2
Remove Deprecated Config class support by @vitalik in https://github.com/vitalik/django-ninja/pull/1528
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.4.3t...v1.5.0b1
## What's Changed - pydantic2.12 compatibility - #1572 regression fix
Nothing published for this version
uuidstr url converter instead of shadowing django uuid by @vitalik in https://github.com/vitalik/django-ninja/pull/1453
uuidstr url converter instead of shadowing django uuid by @vitalik in https://github.com/vitalik/django-ninja/pull/1453--ensure-ascii during export by @vitalik in https://github.com/vitalik/django-ninja/pull/1473Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.4.1...v1.4.2
Nothing published for this version
fix: added missing await to get response fix_request_files_middlewar… by @caspel26 in https://github.com/vitalik/django-ninja/pull/1439
await to get response fix_request_files_middlewar… by @caspel26 in https://github.com/vitalik/django-ninja/pull/1439Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.4.0...v1.4.1
request.FILES in non-POST request - basically there is a long story where Django does not set request.FILES for methods like PUT, PATCH Users were jus
File uploads
request.FILES in non-POST request - basically there is a long story where Django does not set request.FILES for methods like PUT, PATCH
Users were just struggling to understand why their API endpoints are not validating and had to add special middleware that fixes that
Now django ninja will automatically notify user in that case and will ask to add that middleware when user uses non-POST methods
Pagination
Validation errors
Requests that fail validation raise ninja.errors.ValidationError (not to be confused with pydantic.ValidationError).
ValidationErrors have a default exception handler that returns a 422 (Unprocessable Content) JSON response of the form:
{
"detail": [ ... ]
}
Error context Now you can customise it by overwriting the following method:
class CustomNinjaAPI(NinjaAPI):
def validation_error_from_error_contexts(self, error_contexts): ...
pattern= Support
Regex pattern fully compatible with latest pydantic, allows you to add extra validation in arguments:
@router.get("/path/param-pattern/{item_id}")
def get_path_param_pattern(request, item_id: str = Path(..., pattern="^foo")):
return item_id
Custom Django model fields
there is now a standard way to register custom django field to pydantic type:
from ninja.orm import register_field
register_field("MyCustomField", int)
Throttling
Throttling now supports multi-period intervals, such as 5/30s, 10/5m, and 100/2h. Previously, the throttling implementation only allowed single-period intervals (e.g., 5/s, 100/d), which limited the granularity and flexibility of rate limits.
make fmt and the pipeline to use the same --preview option of Ruff by @c4ffein in https://github.com/vitalik/django-ninja/pull/1274Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.3.0...v1.4.0b1
Fix for request.FILES Population on Non-POST Methods by @vitalik in https://github.com/vitalik/django-ninja/pull/1423
make fmt and the pipeline to use the same --preview option of Ruff by @c4ffein in https://github.com/vitalik/django-ninja/pull/1274Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.3.0...v1.4.0b1
This version brings few enahcments
This version brings few enahcments
class SchemaWithCustomSerializer(Schema):
test1: str
test2: str
@model_serializer(mode="wrap")
def ser_model(self, handler, info):
request = info.context["request"] # !!!
response_status = info.context["response_status"] # !!!
return handler(self)
PatchDict you can quickly define schemas with all optional fields and use it as dict with ONLY fields that were passed in request payload (aka patch requests)from ninja import PatchDict
class SomeSchema(Schema):
name: str
description: str
due_date: date
# Note all fields a required
@api.patch("/patch")
def modify_data(request, payload: PatchDict[SomeSchema]):
# payload ! <--- payload is a type of dict and contains only keys that were passed in request body (validated with SomeSchema)
for attr, value in payload.items():
setattr(obj, attr, value)
obj.save()
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.2.2...v1.3.0
Fix unchanging field bug when validate assignment true by @austinpgraham in https://github.com/vitalik/django-ninja/pull/1232
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.2.1...v1.2.2
Fixed throttling in async mode
Fixed throttling in async mode
Async Pagination support by @jamesrkiger
with most notable
FilterSchema by @max-muoto in https://github.com/vitalik/django-ninja/pull/1039decorate_view to resolve Pyright Issues by @max-muoto in https://github.com/vitalik/django-ninja/pull/1126Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.1.0...v1.2.0
Replace deprecated Pydantic method by @scott-8 in https://github.com/vitalik/django-ninja/pull/922
description declared has type str but is used as type None by @luca-digrazia in https://github.com/vitalik/django-ninja/pull/530Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.0.1...v1.1.0
Fixed from_orm compatibility
Fixed from_orm compatibility
…version 1 which might have few deprecations or breaking changes on pydantic level
Read more details and examples here https://django-ninja.dev/whatsnew_v1/
or watch overview video :
<a href="https://youtu.be/GrIpDXPG41o"><img width="500" alt="SCR-20231116-qmoj" src="https://github.com/vitalik/django-ninja/assets/95222/06958fbf-6d3a-4f33-aa76-7a29279c9959"></a>
Annotated[] syntax support)Unfortunately Django ninja integrates very deep into pydantic core with Schema class, so it is not possible to keep both pydantic v1 and v2 supported - and that is why ninja now bumps to version 1 which might have few deprecations or breaking changes on pydantic level
From Django ninja side I tried to make this upgrade as smooth as possible, if you use standard APIs without lot of magic - most likely upgrade should be without any code change
@AlTosterino @AmiZya @Kristinus @ddahan @dipbazz @ivoire @lilleswing @marius-mather @pavel-beaufort @pawelngei @scott-8 @skokado @vincentdavis @vpoulailleau @yasoob
Thank you !
Full Changelog: https://github.com/vitalik/django-ninja/compare/v0.22.2...v1.0
…version 1 which might have few deprecations or breaking changes on pydantic level
This looks like the final pre-release - and I'm happy to report that beta versions was successfully tested by multiple companies in production environments
Annotated[] syntax support)Unfortunately Django ninja integrates very deep into pydantic core with Schema class, so it is not possible to keep both pydantic v1 and v2 supported - and that is why ninja now bumps to version 1 which might have few deprecations or breaking changes on pydantic level
From Django ninja side I'm trying to make this upgrade as smooth as possible, if you use standard APIs without lot of magic - most likely upgrade should be without any code change
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.0b2...v1.0rc
…version 1 which might have few deprecations or breaking changes on pydantic level
Warning: This is a pre-release of Django Ninja V1
This is the last change before 1.x release
This version introduces a new cleaner way to mark requests parameters
f.e.
def some_form(request, data: Form[SomeSchema]):
...
instead of
def some_form(request, data: SomeSchema = Form(...)):
...
This syntax looks cleaner/short and has the same code completion hints in popular editors.
On the other hand the old syntax is still supported so you can easy port your project to a newer django-ninja version
What's new in 1.x
Annotated[] syntaxUnfortunately Django ninja integrates very deep into pydantic core with Schema class, so it is not possible to keep both pydantic v1 and v2 supported - and that is why ninja now bumps to version 1 which might have few deprecations or breaking changes on pydantic level
From Django ninja side I'm trying to make this upgrade as smooth as possible, if you use standard APIs without lot of magic - most likely upgrade should be without any code change
Full Changelog: https://github.com/vitalik/django-ninja/compare/v1.0b1...v1.0b2
…version 1 which might have few deprecations or breaking changes on pydantic level
Warning: This is a pre-release of Django Ninja V1
On the other hand this is a beta release, so no more dramatic changes expected - mostly bug fixes
There is only one major syntax thing that I'm still considering to add to 1.0 - shorter annotations - #746 - Please take a look and give your vote/thoughts
What's new
Annotated[] syntaxUnfortunately Django ninja integrates very deep into pydantic core with Schema class, so it is not possible to keep both pydantic v1 and v2 supported - and that is why ninja now bumps to version 1 which might have few deprecations or breaking changes on pydantic level
From Django ninja side I'm trying to make this upgrade as smooth as possible, if you use standard APIs without lot of magic - most likely upgrade should be without any code change
…version 1 which might have few deprecations or breaking changes on pydantic level
Warning: This is a pre-release of Django Ninja V1
You probably should not use this version in production
What's new v1a3
What's new v1a2
What's new v1a1
Unfortunately Django ninja integrates very deep into pydantic core with Schema class, so it is not possible to keep both pydantic v1 and v2 supported - and that is why ninja now bumps to version 1 which might have few deprecations or breaking changes on pydantic level
From Django ninja side I'm trying to make this upgrade as smooth as possible, if you use standard APIs without lot of magic - most likely upgrade should be without any code change
…version 1 which might have few deprecations or breaking changes on pydantic level
Warning: This is a pre-release of Django Ninja V1
You probably should not use this version in production
What's new v1a2
What's new v1a1
Unfortunately Django ninja integrates very deep into pydantic core with Schema class, so it is not possible to keep both pydantic v1 and v2 supported - and that is why ninja now bumps to version 1 which might have few deprecations or breaking changes on pydantic level
From Django ninja side I'm trying to make this upgrade as smooth as possible, if you use standard APIs without lot of magic - most likely upgrade should be without any code change
…version 1 which might have few deprecations or breaking changes on pydantic level
Warning: This is a pre-release of Django Ninja V1
You probably should not use this version in production
What's new
Unfortunately Django ninja integrates very deep into pydantic core with Schema class, so it is not possible to keep both pydantic v1 and v2 supported - and that is why ninja now bumps to version 1 which might have few deprecations or breaking changes on pydantic level
From Django ninja side I'm trying to make this upgrade as smooth as possible, if you use standard APIs without lot of magic - most likely upgrade should be without any code change
Fixed schema generation bug #774
Nothing published for this version
ModelSchema now support config.model_fields_optional to mark some or specific fields to be not required in schema
pyproject.toml by @baseplate-admin in https://github.com/vitalik/django-ninja/pull/736Full Changelog: https://github.com/vitalik/django-ninja/compare/v.0.21.0...v0.22.0
Somewhat advanced filtering with FilterSchema by @l1b3r in https://github.com/vitalik/django-ninja/pull/673
Full Changelog: https://github.com/vitalik/django-ninja/compare/v0.20.0...v.0.21.0
Speedup code reload by @hiaselhans in https://github.com/vitalik/django-ninja/pull/624
pyproject.toml by @baseplate-admin in https://github.com/vitalik/django-ninja/pull/563flit build by @baseplate-admin in https://github.com/vitalik/django-ninja/pull/564Full Changelog: https://github.com/vitalik/django-ninja/compare/v0.19.1...v0.20.0
Declare the AuthenticationError exception class in __all__ by @duducp in https://github.com/vitalik/django-ninja/pull/489
.from_orm method by @cltrudeau in https://github.com/vitalik/django-ninja/pull/503Full Changelog: https://github.com/vitalik/django-ninja/compare/v.0.19.0...v0.19.1
docs decorator by @vitalik in https://github.com/vitalik/django-ninja/pull/488
get_operation_url_name by @SmileyChris in https://github.com/vitalik/django-ninja/pull/486Full Changelog: https://github.com/vitalik/django-ninja/compare/v.0.18.0...v.0.19.0
Please welcome the new Django Ninja version it has lot of fixes and improvements
Hello
Please welcome the new Django Ninja version it has lot of fixes and improvements
Most notable a HttpResponse typed argument by @SmileyChris
Now you can manage response behaviour (cookies, headers, streaming) flixible:
@api.post("/boop")
def boop(request, response: HttpResponse): # !
response.set_cookie("beep", "boop") # !
return True
signature.details.is_collection_type by @flaeppe in https://github.com/vitalik/django-ninja/pull/434Full Changelog: https://github.com/vitalik/django-ninja/compare/v0.17.0...v0.18.0
This release brings few long awaited features:
This release brings few long awaited features:
Now you can access orm instance attributes inside schema with resolvers:
class TaskSchema(Schema):
title: str
is_completed: bool
owner: Optional[str]
lower_title: str
@staticmethod
def resolve_owner(obj): # <------- !!!!!!
if not obj.owner:
return
return f"{obj.owner.first_name} {obj.owner.last_name}"
def resolve_lower_title(self, obj): # <-------- !!!!!!
return self.title.lower()
Field aliases now support django template variables dotted syntax:
class TaskSchema(Schema):
...
last_comment: str = Field(..., alias="comment_set.0.text")
Thanks to @SmileyChris
Now default paginated output returns a dict with items and count
You can now override both input and output schemas for custom pagination:
class CustomPagination(PaginationBase):
class Input(Schema):
page: int
class Output(Schema):
items: List[Any]
total_pages: int
current_page: int
def paginate_queryset(self, queryset, pagination: Input, **params):
return {
'items': ...,
'total_pages': ...,
'current_page': ...,
}
**kwargs not required anymore for pagination by @mom1 #285Full Changelog: https://github.com/vitalik/django-ninja/compare/v0.16.2...v0.17.0
Pydantic 1.9.0 support #310 by @antonrh
Many documentaion fixes and improvements by:
Resolve #229 & #240 reporting dev errors under django dev-server (#242 by @stephenrauch)
Generating OpenAPI automatically created schema names changed for duplicated names (see #230) Now instead of silence (or exceptions on other cases) dj
OpenAPI schemas names
Generating OpenAPI automatically created schema names changed for duplicated names (see #230) Now instead of silence (or exceptions on other cases) django-ninja will just add sequential number suffix to the schema name in OpenAPI spec. For example if you already have schema called "User" and in some other module you create another "User" schema - the second will have name "User2" in openapi json.
Other
Introduced ModelSchema - declarative way to create schemas from django models
Major changes
Other changes
This is a very nice release, which includes some new functionality and fixes And more important there are lot of people contributed to this update Tha
Hello Everyone,
This is a very nice release, which includes some new functionality and fixes And more important there are lot of people contributed to this update Thank you
Nothing published for this version
fixed schema generation bug
fixed schema generation bug (#145)
Fixed create_schema ValueError on pydantic 1.8.2
create_schema ValueError on pydantic 1.8.2 (#135)custom_fields in create_schema to override or add fieldsBetter console debugging and prints removal(#64 #115 #119)
One column per quarter.