Django Ninja
Django Ninja is a fast, modern web framework for building APIs with Django using Python type hints, Pydantic, and automatic OpenAPI documentation. It aims for high performance and developer friendliness, similar to FastAPI, while leveraging Django's ecosystem. The library maintains a regular release cadence with frequent updates and bug fixes.
Warnings
- breaking Django Ninja v1.0 and later versions require Pydantic V2. Projects upgrading from older Django Ninja versions (0.x) or using Pydantic V1 will encounter breaking changes due to Pydantic's major rewrite.
- gotcha Directly calling Django ORM methods (e.g., `MyModel.objects.all()`) within `async` API views will block the event loop and raise an error. The Django ORM is not fully async-native yet.
- deprecated The previous method of returning a tuple `(status_code, body)` to specify HTTP status codes in responses is deprecated.
- breaking As of v1.6.0, routers became idempotent and reusable. While this is an enhancement, it changes behavior around mounting the same router multiple times. Previous workarounds or reliance on non-idempotent behavior might need review.
- gotcha Standard Django decorators (e.g., `@cache_page`, `@transaction.atomic`) do not directly integrate with Django Ninja operation functions without explicit wrapping.
Install
-
pip install django-ninja
Imports
- NinjaAPI
from ninja import NinjaAPI
- Router
from ninja import Router
- ModelSchema
from ninja import ModelSchema
- Query
from ninja import Query
- Path
from ninja import Path
- Body
from ninja import Body
- File
from ninja import File
- UploadedFile
from ninja.files import UploadedFile
Quickstart
from django.contrib import admin
from django.urls import path
from ninja import NinjaAPI
# In your Django project's main urls.py:
# from .api import api # Assuming api.py is next to urls.py
# urlpatterns = [
# path('admin/', admin.site.urls),
# path('api/', api.urls) # Mount the NinjaAPI
# ]
# Create an api.py file in your Django project's root directory (next to urls.py)
# api.py
api = NinjaAPI(title="My Awesome API", version="1.0.0")
@api.get("/hello")
def hello(request):
return "Hello from Django Ninja!"
@api.get("/add")
def add(request, a: int, b: int):
return {"result": a + b}