Skip to content

Test PyPI version PyPI version PyPI version PyPI version Codecov Downloads

Django Ninja Extra Documentation

Django Ninja Extra provides a class-based approach along with additional features that will accelerate your RESTful API development using Django Ninja.

Key features:

All Django-Ninja features:

  • Simple: Designed to be easy to use and intuitive.
  • Fast execution: Thanks to Pydantic and async support, it delivers very high performance.
  • Fast coding: Type hints and automatic documentation let you focus on business logic.
  • Standards-based: Based on standards: OpenAPI (formerly Swagger) and JSON Schema.
  • Django friendly: (Obviously) well integrated with Django core and ORM.

Plus Extra:

  • Class-based: Design your APIs in a class-based manner.
  • Permissions: Easily secure access endpoints via permissions and authentication defined at the route level or controller level.
  • Dependency injection: Controller classes support using Python Injector or django_injector. This allows you to inject API dependency services into APIController classes and use them where needed.

Version Requirements

  • Python >= 3.6
  • django >= 2.1
  • pydantic >= 1.6
  • Django-Ninja >= 0.16.1

For the full documentation, visit this link.

Installation

pip install django-ninja-extra
After installation, add ninja_extra to your INSTALLED_APPS

INSTALLED_APPS = [
    ...,
    'ninja_extra',
]

Usage

In your Django project, create a new api.py file next to urls.py:

from ninja_extra import NinjaExtraAPI, api_controller, http_get

api = NinjaExtraAPI()

# Function-based definition
@api.get("/add", tags=['Math'])
def add(request, a: int, b: int):
    return {"result": a + b}

# Class-based definition
@api_controller('/', tags=['Math'], permissions=[])
class MathAPI:

    @http_get('/subtract',)
    def subtract(self, a: int, b: int):
        """Subtracts a from b"""
        return {"result": a - b}

    @http_get('/divide',)
    def divide(self, a: int, b: int):
        """Divides a by b"""
        return {"result": a / b}

    @http_get('/multiple',)
    def multiple(self, a: int, b: int):
        """Multiples a with b"""
        return {"result": a * b}

api.register_controllers(
    MathAPI
)

Now go to urls.py and add the following:

...
from django.urls import path
from .api import api

urlpatterns = [
    path("admin/", admin.site.urls),
    path("api/", api.urls),  # <---------- !
]

Interactive API documentation

Now go to http://127.0.0.1:8000/api/docs

You will see the automatic interactive API documentation (powered by Swagger UI):

Swagger UI

Tutorials


本文总阅读量次