An API namespace keeps endpoint names distinct when a Django Ninja API is versioned. Give an endpoint a name, and combine it with the API version to create its lookup name. section 11.2.2
Without a version argument, Ninja uses the namespace api-1.0.0:. With version="1.0", it uses api-1.0:. The endpoint name follows the colon, so url_name="fetch_venue" becomes api-1.0:fetch_venue. section 11.2.2
Reversing a namespaced endpoint
A Venue serializer can call reverse("api-1.0:fetch_venue", args=[obj.id]) to produce /api/v1/bands/venue/1/. The matching endpoint sets url_name="fetch_venue" on its Ninja route. section 11.2.2
Listing 11.7 API endpoint for fetching a Venue object
# RiffMates/bands/api.py
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.text import slugify
from ninja import Router, ModelSchema
from bands.models import Venue
router = Router() #1
class VenueOut(ModelSchema):
slug: str #2
url: str
class Meta:
model = Venue
fields = ["id", "name", "description"] #3
@staticmethod
def resolve_slug(obj): #4
slug = slugify(obj.name) + "-" + str(obj.id)
return slug
@staticmethod
def resolve_url(obj): #5
url = reverse("api-1.0:fetch_venue", args=[obj.id, ])
return url
@router.get("/venue/{venue_id}/",
response=VenueOut,
url_name="fetch_venue") #6
def fetch_venue(request, venue_id):
venue = get_object_or_404(Venue, id=venue_id)
return venue
Inspect the complete route and serializer together to see how the endpoint name becomes part of a reverse lookup. section 11.2.2
