Ga naar inhoud

Test PyPI version PyPI version PyPI version PyPI version Codecov Downloads

Django Ninja Extra-documentatie

Django Ninja Extra biedt een class-based aanpak samen met extra functies die je RESTful API-ontwikkeling met Django Ninja versnellen.

Belangrijkste functies:

Alle Django-Ninja-functies:

  • Eenvoudig: ontworpen om gemakkelijk en intuïtief te gebruiken.
  • Snelle uitvoering: dankzij Pydantic en async-ondersteuning levert het zeer hoge prestaties.
  • Snel coderen: type hints en automatische documentatie laten je je richten op de bedrijfslogica.
  • Gebaseerd op standaarden: gebaseerd op standaarden: OpenAPI (voorheen Swagger) en JSON Schema.
  • Django-vriendelijk: (uiteraard) goed geïntegreerd met de Django-kern en de ORM.

Plus Extra:

  • Class-based: ontwerp je API's op een class-based manier.
  • Machtigingen: beveilig toegangsendpoints eenvoudig via machtigingen en authenticatie, gedefinieerd op route- of controllerniveau.
  • Dependency injection: controllerklassen ondersteunen het gebruik van Python Injector of django_injector. Zo kun je API-afhankelijkheidsdiensten injecteren in APIController-klassen en ze waar nodig gebruiken.

Versievereisten

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

Voor de volledige documentatie, bezoek deze link.

Installatie

pip install django-ninja-extra
Voeg na installatie ninja_extra toe aan je INSTALLED_APPS

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

Gebruik

Maak in je Django-project een nieuw bestand api.py aan naast 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
)

Ga nu naar urls.py en voeg het volgende toe:

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

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

Interactieve API-documentatie

Ga nu naar http://127.0.0.1:8000/api/docs

Je ziet de automatische interactieve API-documentatie (aangedreven door Swagger UI):

Swagger UI

Tutorials


Paginaweergaven: