liveBook · Manning

Django Ninja

As explained in Django in Action

Django Ninja is a Django library for defining and implementing web APIs with typed request and response schemas.

Django Ninja is a third-party Django library for building REST APIs: URL- and HTTP-based interfaces that let mobile apps, single-page applications, and other systems access project data. It keeps API endpoints close to familiar Django view functions while reducing repetitive serialization code. section 11.0 section 11.2

Create one NinjaAPI object for an API, collect related endpoints in Router objects, register each router, and mount api.urls with Django’s path(). Router decorators such as @router.get turn ordinary functions into HTTP endpoints. Install it with pip install django-ninja; it does not need an INSTALLED_APPS entry. section 11.2

A first endpoint

A router can answer GET requests with a small function. After the router is registered under an API prefix, its route becomes part of the project’s API URL space—an approachable first step before returning database objects. section 11.2

For database-backed endpoints, query an ORM model, optionally change it, and return it. Ninja mostly serializes model objects to JSON automatically and can use Python type hints for non-model fields. ModelSchema shapes required fields from the ORM model. section 11.2 section 11.2.7

Use HTTP-method decorators to express common API operations:

  • Use PUT when a client sends every field; loop through the validated payload, set each attribute, save the model, and return it. section 11.2.7
  • Use PATCH when only changed fields should be sent, but provide a custom schema with Optional type hints for fields that would otherwise be required. section 11.2.7
  • Use DELETE to fetch the target object, delete it, and return a success response. section 11.2.7
Listing 11.14 A update endpoint for venues
# RiffMates/bands/api.py
...

@router.put("/venue/{venue_id}/", #1
    response=VenueOut, auth=api_key)  #2
def update_venue(request, venue_id, payload:VenueIn):  #3
    venue = get_object_or_404(Venue, id=venue_id)  #4
    for key, value in payload.dict().items():
        setattr(venue, key, value)  #5

    venue.save()  #6
    return venue

This PUT endpoint shows the complete update flow: identify a venue from the URL, apply payload fields with setattr(), save it, and return the updated object. section 11.2.7

Django Ninja favors concise JSON REST APIs. Django REST Framework follows similar ideas but generally uses classes and more code; it offers richer response-format support when JSON is not enough. section 11.3

How Django in Action covers it

How deep it goes
Walks through installation, routing, serialization, and PUT, PATCH, and DELETE endpoint implementation; defers richer non-JSON API formats to Django REST Framework.
Examples
Uses RiffMates hello-world, venue-update, and venue-delete endpoints to demonstrate routers, payloads, model changes, and responses.
What it assumes
Assumes a Django project with URL routing and ORM models while introducing Ninja installation, API objects, routers, and endpoint decorators.
What you can do after
Build it from scratch by mounting routers, defining decorated endpoints, serializing model data, and implementing PUT, PATCH, and DELETE operations.
How it connects
Connects REST APIs with HTTP methods, Django ORM models, JSON serialization, Python type hints, URL routing, and Django REST Framework.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.