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
