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.
pip install django-ninjaVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates creating a basic API endpoint. Define a `NinjaAPI` instance, then use decorator functions (e.g., `@api.get`) to define API routes. Parameters with type hints are automatically validated and converted. The API instance's `.urls` should be included in your Django project's `urlpatterns`.
Upgrade Pydantic to V2 and refactor Pydantic models according to Pydantic V2 migration guides. Django Ninja's `ModelSchema.Meta` class replaces `BaseModel.Config` for model-based schemas.
Wrap all blocking (synchronous) ORM calls and other sync I/O operations with `sync_to_async` from `asgiref.sync`. For example: `queryset = await sync_to_async(MyModel.objects.all)()` or `obj = await sync_to_async(MyModel.objects.get)(pk=id)`.
Use the `Status` class explicitly for returning responses with custom HTTP status codes. For example, `return Status(200, {'message': 'Success'})`.Review any code that mounts the same `Router` instance multiple times to ensure the new idempotent behavior (where decorators, auth, tags, and throttling are fully isolated between mounts) aligns with expectations. This generally resolves previous errors for such patterns.
For function-based operations, you might need to manually wrap the Django decorator around the `django-ninja` decorator, or use `router.add_decorator` with a custom universal decorator that handles both sync/async. The `decorate_view` utility or custom middleware might also be necessary for certain scenarios. Refer to the 'Decorators' section of the official documentation.