Django Ninja is a web framework for building APIs with Django and Python 3.6+ type hints.
Key features:
pip install django-ninja
Start a new Django project (or use an existing one)
django-admin startproject apidemo
in urls.py
from django.contrib import admin
from django.urls import path
from ninja import NinjaAPI
api = NinjaAPI()
@api.get("/add")
def add(request, a: int, b: int):
return {"result": a + b}
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", api.urls),
]
Now, run it as usual:
./manage.py runserver
Note: You don't have to add Django Ninja to your installed apps for it to work.
Open your browser at http://127.0.0.1:8000/api/add?a=1&b=2
You will see the JSON response as:
{"result": 3}
Now you've just created an API that:
/api/add
a
and b
Now go to http://127.0.0.1:8000/api/docs
You will see the automatic, interactive API documentation (provided by the OpenAPI / Swagger UI or Redoc):
In summary, you declare the types of parameters, body, etc. once only, as function parameters.
You do that with standard modern Python types.
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
Just standard Python 3.6+.
For example, for an int
:
a: int
or, for a more complex Item
model:
class Item(Schema):
foo: str
bar: float
def operation(a: Item):
...
... and with that single declaration you get: