Django Ninja Extra

0.31.4 · active · verified Thu Apr 16

Django Ninja Extra is a powerful extension for Django Ninja, providing class-based utilities and advanced features for building REST APIs. It augments Django Ninja with API controllers, an advanced permission system (similar to Django REST Framework), dependency injection, and a service layer for business logic. The library is actively maintained, with its current version being 0.31.4, and follows a frequent release cadence to support the latest Django and Django Ninja versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic API using `NinjaExtraAPI` and define a class-based `APIController` with two simple GET routes. It includes the necessary Django setup for a runnable example. The controller is registered with the main API instance, and its routes are then exposed via Django's URL configuration. Remember to add 'ninja_extra' to your `INSTALLED_APPS`.

import os
from django.conf import settings
from django.urls import path
from ninja_extra import NinjaExtraAPI, api_controller, http_get

if not settings.configured:
    settings.configure(
        DEBUG=True,
        INSTALLED_APPS=[
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'ninja_extra',
        ],
        ROOT_URLCONF=__name__,
        SECRET_KEY='a-very-secret-key',
        TEMPLATES=[{
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'APP_DIRS': True,
        }],
    )

api = NinjaExtraAPI()

@api_controller("/items", tags=["Items"])
class ItemController:
    @http_get("/")
    def list_items(self):
        return [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}]

    @http_get("/{item_id}")
    def get_item(self, item_id: int):
        return {"id": item_id, "name": f"Item {item_id}"}

api.register_controllers(ItemController)

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

# To run this in a Django project, you'd integrate `api.urls` into your project's `urls.py`:
# from django.urls import path, include
# from .api import api # Assuming your api setup is in api.py
# urlpatterns = [
#     path("api/", api.urls),
# ]
# Remember to add 'ninja_extra' to your INSTALLED_APPS in settings.py

view raw JSON →