ContentsClose contents
Pre-release
Chapter 49 · API views, generic views, viewsets, and routersCHAPTER 49

Complete six-part pre-release for review. One package: drf-spectacular 0.30.0. The practice file shows a ModelViewSet letting a member delete a published event. The generated OpenAPI file replaces the hand-written one. Three earlier tests change on purpose (declared in the chapter).

Working towards: API and integrations (Chapter 54). Another program can list published events through an API and receive signed notifications when an event changes. All milestones

CHAPTER FORTY-NINE

API views, generic views, viewsets, and routers

Stage 6: APIs and real-time updates (Chapters 47 to 54)

Prerequisites: Chapters 9 to 48, including the Chapter 48 project with its 670 passing tests, DRF with its strict defaults, the serializers, the organizer’s own events with If-Match and dry runs, and Event.edit() shared by the edit page and the API

What you’ll build: one resource written three ways and compared; the organizer’s own events as one viewset, with only the actions the contract lists, routed by a router; publish, cancel, and deleting a draft through the same model methods as the site’s pages; the OpenAPI file made from the code, with a test that fails if the two disagree; DRF’s browsable pages in development only; and each event’s API address, ready to copy, on My events

Why This Matters

The organizer’s own events now have create, read, and change, in two views. The contract promises more: the list of my events, publish, cancel, and deleting a draft. Sam’s agent needs all of them, and two more views would make four classes for one resource, each repeating how to find the event and check the organizer.

DRF offers a bigger tool for exactly this: a viewset, one class holding every action on a resource, and a router that gives each action its address. Many tutorials start there, with ModelViewSet and DefaultRouter: five lines, and every action exists. That is the danger. Every action exists, including the ones nobody planned. Step 3 shows it: with the project’s own defaults, a member who organizes nothing deletes a published event through a ModelViewSet, and the router adds addresses nobody asked for.

This chapter compares the ways DRF offers to write API views, by running the same resource three ways, then chooses on purpose: generic views for the public reads, and for the organizer’s events a viewset with only the actions the contract lists. It then makes the OpenAPI file from the code, so the description an agent reads can no longer drift from what the API does.

By the end of the chapter, you will be able to:

  • trace a request through DRF’s layers: router, view, authentication, permission, serializer, response;
  • compare APIView, generic views, and viewsets on the same resource, and say what each adds;
  • read the addresses a router makes, and choose the router that makes only the ones you want;
  • write a viewset with exactly the actions a contract lists, including custom ones with @action;
  • make an OpenAPI file from the code with drf-spectacular, and test that it stays current;
  • keep development tools, such as DRF’s browsable pages, out of production with a system check.

Out of scope: tokens and scopes (Chapter 50), paging and filtering (Chapter 51), webhooks (Chapter 52), and generating client code from the OpenAPI file (not planned).

PAGE 001

What You Need to Know

DRF’s layers

A request to a DRF view passes through more steps than a Django view. Figure 49.1 shows them in order.

Six numbered cards in order. 1, URL: the router or path() picks the view and the action. 2, initial(): authentication works out who is asking, from the session. 3, permissions: IsAuthenticated, or AllowAny where a view says so. 4, the action: list, retrieve, partial_update, or an @action, calling the model’s methods. 5, the serializer: data in and out. 6, the response, rendered as JSON, or as the browsable page while developing; any exception goes to Otahque’s handler as problem details.
Figure 49.1 — A request through DRF.

Under the Hood: dispatch(), initial(), and handle_exception()

APIView.dispatch() wraps Django’s own: it turns the request into DRF’s Request (which parses JSON into request.data), then calls initial(), which runs authentication, permissions, and throttles, in that order. Only then does it call the method’s handler. Any exception from any of these goes to handle_exception(), which calls EXCEPTION_HANDLER, Otahque’s problem-details handler since Chapter 48. That order explains two things this chapter’s tests see: a visitor gets 403 before DRF even checks whether the method is allowed, and every error, from any layer, has the same shape.

Three ways to write a resource

DRF offers three levels of view, each built on the one before (Table 49.1).

Table 49.1 — Three levels of DRF view
Level What you write What it gives
APIView A method per HTTP verb: get(), patch() Nothing assumed; every step by hand
Generic view queryset, serializer_class, and a base such as RetrieveUpdateDestroyAPIView The usual actions, from mixins; one view per address
ViewSet with a router Actions: list, retrieve, partial_update, destroy, @action One class per resource; the router makes the addresses

New Concept: a viewset and a router

What problem exists? A resource with many actions needs several views and several URL patterns, each repeating how to find the object and who may act on it.

What did people do before? One generic view per address, as Chapter 48 did, with the repeated parts in a mixin.

What is it? A viewset is a class whose methods are actions (list, create, retrieve, partial_update, destroy, and any marked @action), not HTTP verbs. A router reads a viewset and makes its URL patterns: my/events/ for list and create, my/events/{id}/ for the rest, and my/events/{id}/publish/ for an @action. ModelViewSet is a viewset with every action already written.

Why use it? One place for one resource’s rules, and addresses that follow one pattern.

Now let’s use it. Step 3 tries ModelViewSet with DefaultRouter; Step 5 writes the one Otahque keeps.

The same resource, written three ways as Step 3’s practice file writes it, is drawn in Figure 49.2.

Three columns, one per style, over a shared bar: the same resource, one event of mine, in ways.py. APIView: get() written out; allowed: GET, OPTIONS. Generic view: RetrieveUpdateDestroyAPIView with a queryset; allowed: GET, PUT, PATCH, DELETE, OPTIONS, more than asked for. ModelViewSet with DefaultRouter: every action, plus addresses with .json suffixes and an API root.
Figure 49.2 — Three styles, one contract.

What a router adds

Two routers come with DRF. DefaultRouter makes, for each viewset, the list and detail addresses, a copy of each ending in a format suffix (my/events/7.json), and an API root page listing every resource. SimpleRouter makes only the list and detail addresses, and one per @action. Figure 49.3 compares them for Otahque’s viewset; the proof for L2 prints both.

Two panels. DefaultRouter: my/events/, my/events.json, my/events/7/, my/events/7.json, the publish and cancel addresses each with a .json twin, an API root, and its .json twin. SimpleRouter: my/events/, my/events/7/, my/events/7/publish/, my/events/7/cancel/. A note: every extra address is one more thing to test and secure.
Figure 49.3 — What each router makes.

The router routes only the actions a viewset defines, and the viewset answers only the methods in its http_method_names. Those two facts are the whole design of Step 5: define exactly the contract’s actions, list exactly its methods, and use the router that adds nothing else (D49.1).

One path for every action

Chapter 48 moved editing into Event.edit(), so the edit page and the API share every step. Publishing, cancelling, and deleting have the same problem: the site’s views record the action and, for a cancel, email every member holding a place, around the model’s publish() and cancel(). Step 4 moves those into publish_by(), cancel_by(), and delete_by(), each taking the person acting and a dry run, before the viewset calls them. Then a cancel from Sam’s agent records and emails exactly as Sam’s Cancel button does, and its dry run counts the emails it would send.

A contract the code writes

Chapters 47 and 48 wrote docs/api/openapi.yaml by hand, and the tests caught the fields drifting. Each new endpoint made it longer by a page.

New Tool: drf-spectacular

What problem exists? A hand-written OpenAPI file grows with every endpoint, and its errors, parameters, and headers drift from the code.

What did people do before? DRF’s own schema generator, which DRF’s documentation now calls deprecated, or drf-yasg, which describes the older OpenAPI 2.

What is it? drf-spectacular makes an OpenAPI 3 file (3.0 or 3.1) by reading DRF’s views and serializers: their addresses, methods, fields, and types. @extend_schema adds what it cannot see, such as a summary, the errors a view can return, or a header such as If-Match. DRF’s documentation recommends it. Version 0.30.0 (July 2026) lists Django 6.0 as its newest tested release; it was checked on Django 6.1.2 for this chapter, with SQLite and PostgreSQL, and is checked again at the Django 6.2 upgrade.

Why use it? The file comes from the code, so a test can insist they agree; and an agent reading it sees each operation’s name, summary, and errors.

Now let’s use it. Step 6 makes docs/api/openapi.yaml with manage.py spectacular, and a test fails whenever the code would make a different one (N49.3).

Tools for development only

DRF’s browsable API is an HTML page for every address, with forms to send requests: useful while building, and a gift to anyone probing a production site. Otahque turns it on only when DEBUG is on, and, as Chapter 40 did for other settings that differ in production, adds a deploy check, otahque.W005, that warns if it is ever on where DEBUG is off.

In practice: choosing a view style in a team

Situation. A team’s API grows from three endpoints to thirty, written by different people over a year.

Application. A rule written down in an ADR (“every API view states its methods; a router only routes actions a viewset defines”) lets each newcomer write the next endpoint the same way, and lets a reviewer reject a ModelViewSet with one sentence.

Consideration. Viewsets suit resources with the usual actions; when most endpoints are reports or one-off actions, plain generic views with explicit addresses read more clearly. Otahque uses both, for those reasons, and Step 9 records why in ADR-006.

PAGE 002

How We Build It

Start from Chapter 48, in the folder containing manage.py, with Otahque on PostgreSQL 18, 670 passing tests, and the work committed (the last commit is “Rebuild the API with DRF; add writes”). One package is added, drf-spectacular 0.30.0. There is no migration. The new file is one test module; the generated docs/api/openapi.yaml replaces the hand-written one. The settings, the system checks, the API’s serializers, views, and addresses, the events models and views, the My events page, the site’s script and stylesheet, the contract, ADR-006, and three earlier test modules change. The visible result: the organizer’s events answer list, create, read, change, publish, cancel, and delete a draft, from one viewset; the OpenAPI file comes from the code; DRF’s browsable pages show while developing; and My events shows each event’s API address with a Copy button. The commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.

The Custom Way

The Custom Way, in this chapter, is the quickest DRF code a tutorial shows for a resource: ModelViewSet and DefaultRouter. Step 3 runs it beside the other two styles, without adding it to the project, to see what it does with Otahque’s own settings.

The Django Way

The Django Way is to choose: generic views where an address has one job, a viewset with only the contract’s actions where a resource has many, and the model’s methods doing the work in both.

Step 1: Check the starting point

uv run python manage.py test --parallel
Found 670 test(s).
Creating test database for alias 'default'...
...
Ran 670 tests in ...s

OK
git status --short
git log --oneline -1
... Rebuild the API with DRF; add writes

Step 2: Read the layers

Before writing anything, open api/views.py and find, in EventDetail, each layer of Figure 49.1: PublicRead sets the permission (AllowAny) and the methods; the handler, get(), finds the event; get_serializer() turns it into data; and NotFound is turned into a problem by the handler from Chapter 48. Nothing in this step changes a file.

Step 3: One resource, three ways

Save this as ways.py beside manage.py:

"""Three ways to write one resource's views (Chapter 49)."""
from datetime import timedelta

from django.db import transaction
from django.utils import timezone
from rest_framework import generics, viewsets
from rest_framework.response import Response
from rest_framework.routers import DefaultRouter
from rest_framework.test import (
    APIRequestFactory, force_authenticate,
)
from rest_framework.views import APIView

from accounts.models import User
from api.serializers import MyEventSerializer
from events.models import Event


class ByHand(APIView):
    """APIView: each method written out."""

    def get(self, request, pk):
        """Send one event."""
        event = Event.objects.get(pk=pk)
        return Response(MyEventSerializer(event).data)


class Generic(generics.RetrieveUpdateDestroyAPIView):
    """A generic view: methods from its mixins."""

    queryset = Event.objects.all()
    serializer_class = MyEventSerializer


class Everything(viewsets.ModelViewSet):
    """A ModelViewSet: every action, for any event."""

    queryset = Event.objects.all()
    serializer_class = MyEventSerializer


for view in (ByHand, Generic):
    methods = ', '.join(view().allowed_methods)
    print(f'{view.__name__:8}', methods)
router = DefaultRouter()
router.register('my/events', Everything, basename='try')
for url in router.urls:
    print('route', url.pattern)
start = timezone.now() + timedelta(days=30)
with transaction.atomic():
    event = Event.objects.create(
        title='Published', starts_at=start,
        ends_at=start + timedelta(hours=2),
        timezone='Europe/London', location='Leeds',
        capacity=10, status=Event.Status.PUBLISHED)
    member = User.objects.create_user(
        'nobody@example.org', display_name='Nobody')
    request = APIRequestFactory().delete('/')
    force_authenticate(request, member)
    destroy = Everything.as_view({'delete': 'destroy'})
    answer = destroy(request, pk=event.pk)
    print('a member deletes it:', answer.status_code,
          Event.objects.filter(pk=event.pk).exists())
    transaction.set_rollback(True)

It writes “one event of mine” three ways, prints the methods each answers and the addresses a DefaultRouter makes, then, inside a transaction it rolls back, creates a published event and a member with no role, and has the member send DELETE to the ModelViewSet. Run it, then delete the file:

uv run manage.py shell -v 0 -c "exec(open('ways.py').read())"
ByHand   GET, OPTIONS
Generic  GET, PUT, PATCH, DELETE, OPTIONS
route ^my/events/$
route ^my/events\.(?P<format>[a-z0-9]+)/?$
route ^my/events/(?P<pk>[^/.]+)/$
route ^my/events/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$
route
route <drf_format_suffix:format>
a member deletes it: 204 False

ByHand answers what it defines and nothing more. Generic adds PUT and DELETE because its base class has them. The router made six addresses where two were meant, and the member deleted the event: the default permission asks only that someone is signed in, and the ModelViewSet’s queryset is every event. None of that is a bug in DRF; each piece does what it says. Together they do what nobody decided.

Step 4: One path for publish, cancel, and delete

In events/models.py, above delete_draft():

    def publish_by(self, by, dry_run=False):
        """Publish this draft at by's request, recorded.

        The page and the API both publish here (Chapter 49);
        publish() raises ValidationError if it is not ready.
        """
        with transaction.atomic():
            self.publish()
            record(by, AuditEvent.Action.PUBLISH_EVENT, self)
            if dry_run:
                transaction.set_rollback(True)

    def cancel_by(self, by, dry_run=False):
        """Cancel at by's request; return the emails queued.

        Recorded, and every member holding a place is told,
        in one transaction (Chapters 43 and 49).
        """
        from . import emails
        with transaction.atomic():
            self.cancel()
            record(by, AuditEvent.Action.CANCEL_EVENT, self)
            queued = self.deliveries.count()
            emails.event_cancelled(self)
            queued = self.deliveries.count() - queued
            if dry_run:
                transaction.set_rollback(True)
        return queued

    def delete_by(self, by, dry_run=False):
        """Delete this draft at by's request, recorded first.

        The record comes first: deleting clears self.pk.
        """
        with transaction.atomic():
            record(by, AuditEvent.Action.DELETE_EVENT, self,
                   title=self.title)
            self.delete_draft()
            if dry_run:
                transaction.set_rollback(True)

Then the site’s three views use them. In events/views.py, in event_publish(), the try block becomes:

    try:
        event.publish_by(request.user)

in event_cancel():

    try:
        event.cancel_by(request.user)

and in EventDeleteView.form_valid():

        try:
            event.delete_by(self.request.user)

The pages behave as before, and their tests say so:

uv run python manage.py test events registrations --parallel
Found 466 test(s).
Creating test database for alias 'default'...
...
Ran 466 tests in ...s

OK

Step 5: The viewset

The tests first, in api/tests/test_mine.py:

"""The organizer's own events, as one viewset (Chapter 49).

The list, publish, cancel, and deleting a draft, each
through the same model method as the site's page, with a
dry run; and only the methods the contract lists.
"""
from datetime import timedelta

from django.test import TestCase, override_settings
from django.utils import timezone
from rest_framework.test import APIClient

from api.tests.test_writes import MINE
from audit.models import AuditEvent
from config.helpers import in_group, save_event
from events.models import Delivery, Event
from events.tests.test_tasks import QUEUE_ONLY
from registrations.tests.test_registrations import verified


def ready(**changes):
    """Save a draft that could be published."""
    start = timezone.now() + timedelta(days=10)
    fields = {'starts_at': start,
              'description': 'Bring a laptop.',
              'registration_closes_at': start,
              'cancellation_deadline': start,
              'status': Event.Status.DRAFT}
    return save_event(**(fields | changes))


class Mine(TestCase):
    """Sam signed in, with a draft of his own."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = in_group('sam@example.org', 'Organizers')
        cls.raj = in_group('raj@example.org', 'Organizers')

    def setUp(self):
        self.event = ready(title='Clinic')
        self.event.add_organizer(self.sam)
        self.api = APIClient()
        self.api.force_login(self.sam)
        self.address = f'{MINE}{self.event.pk}/'


class ListTests(Mine):
    """GET /api/v1/my/events/."""

    def test_only_my_events_drafts_included(self):
        ready(title='Raj only').add_organizer(self.raj)
        page = self.api.get(MINE)
        titles = [e['title'] for e in page.json()['results']]
        self.assertEqual(titles, ['Clinic'])

    def test_a_member_who_organizes_nothing_gets_403(self):
        self.api.force_login(verified('sai@example.org'))
        page = self.api.get(MINE)
        self.assertEqual(page.status_code, 403)
        self.assertEqual(page.json()['detail'],
                         'Only organizers have events here.')


class ActionTests(Mine):
    """Publish, cancel, and delete, as on the site."""

    def test_publish_a_ready_draft(self):
        page = self.api.post(f'{self.address}publish/')
        self.assertEqual(page.status_code, 200)
        self.assertEqual(page.json()['status'], 'published')
        self.assertEqual(page['ETag'], '"v2"')
        self.assertTrue(AuditEvent.objects.filter(
            action='publish_event').exists())

    def test_a_draft_not_ready_says_why(self):
        self.event.description = ''
        self.event.save()
        page = self.api.post(f'{self.address}publish/')
        self.assertEqual(page.status_code, 422)
        self.assertEqual(page.json()['errors'], [
            {'pointer': '#', 'detail': 'Add a description.'}])

    def test_delete_a_draft(self):
        page = self.api.delete(self.address)
        self.assertEqual(page.status_code, 204)
        self.assertFalse(Event.objects.filter(
            pk=self.event.pk).exists())

    def test_a_published_event_is_not_deleted(self):
        self.event.publish()
        page = self.api.delete(self.address)
        self.assertEqual(page.status_code, 422)
        self.assertTrue(Event.objects.filter(
            pk=self.event.pk).exists())

    def test_dry_runs_change_nothing(self):
        for method, address in [
                ('post', f'{self.address}publish/'),
                ('delete', self.address)]:
            with self.subTest(method):
                page = getattr(self.api, method)(
                    f'{address}?dry_run=true')
                self.assertEqual(page.status_code, 200)
                self.assertTrue(page.json()['dry_run'])
        self.event.refresh_from_db()
        self.assertEqual(self.event.status, 'draft')
        self.assertFalse(AuditEvent.objects.exists())

    def test_put_is_not_routed(self):
        page = self.api.put(self.address, {}, format='json')
        self.assertEqual(page.status_code, 405)
        self.assertEqual(page['Allow'],
                         'GET, HEAD, PATCH, DELETE')


@override_settings(TASKS=QUEUE_ONLY)
class CancelTests(Mine):
    """Cancelling tells every member holding a place."""

    def setUp(self):
        super().setUp()
        self.event.publish()
        for email in ('sai@example.org', 'soni@example.org'):
            self.event.registrations.create(
                member=verified(email))
        self.cancel = f'{self.address}cancel/'

    def test_a_dry_run_counts_the_emails(self):
        page = self.api.post(f'{self.cancel}?dry_run=true')
        self.assertEqual(page.json()['effects'],
                         {'emails': 2})
        self.event.refresh_from_db()
        self.assertEqual(self.event.status, 'published')
        self.assertFalse(Delivery.objects.exists())

    def test_cancel_queues_the_emails(self):
        page = self.api.post(self.cancel)
        self.assertEqual(page.json()['status'], 'cancelled')
        self.assertEqual(Delivery.objects.filter(
            key__startswith='event_cancelled').count(), 2)

test_put_is_not_routed holds the decision: no PUT, and Allow lists exactly the methods the contract has. Run them with the rest of the API’s tests, Chapter 48’s writes among them, which must keep passing:

uv run python manage.py test api
Found 58 test(s).
Creating test database for alias 'default'...
ERROR: test_a_dry_run_counts_the_emails
KeyError: 'effects'
ERROR: test_only_my_events_drafts_included
KeyError: 'results'
FAIL: test_a_draft_not_ready_says_why
AssertionError: 404 != 422
... (8 more like these)
Ran 58 tests in ...s

FAILED (failures=9, errors=2)

In api/views.py, the docstring becomes:

"""The API's views (Chapters 47 to 49).

The public reads, written by hand in Chapter 47, are DRF
generic views since Chapter 48, with the same answers.
The organizer's own events, at /api/v1/my/events/, are
one viewset since Chapter 49: list, create, read, change,
publish, cancel, and delete a draft. Every write goes
through the model's methods, as the site's pages do.
"""

the rest_framework import becomes:

from rest_framework import (
    exceptions, generics, status, viewsets,
)
from rest_framework.decorators import action

and the two classes MyEventCreate and MyEventDetail are replaced by one:

class MyEventViewSet(viewsets.GenericViewSet):
    """The organizer's own events, at /api/v1/my/events/.

    A viewset holds every action on one resource; the
    router (api/urls.py) gives each its address and method.
    It has only the actions the contract lists: no PUT, and
    no deleting a published event, which a ModelViewSet
    would add (Chapter 49).
    """

    serializer_class = MyEventSerializer
    http_method_names = ['get', 'head', 'post', 'patch',
                         'delete']
    lookup_value_regex = r'\d+'

    def get_queryset(self):
        """Return the events the requester organizes now."""
        return Event.objects.organized_by(self.request.user)

    def get_object(self, action=Action.EDIT_EVENT):
        """Return the event if the requester may change it.

        As on the edit page: 404 for a draft they may not
        see, 403 for an event they do not organize, both
        recorded as an attempt at action (Chapter 30).
        """
        return event_to_manage(self.request,
                               self.kwargs['pk'], action)

    def list(self, request):
        """GET: my events, drafts first; 403 for members."""
        if not request.user.has_perm('events.change_event'):
            raise exceptions.PermissionDenied(
                'Only organizers have events here.')
        events = self.get_serializer(self.get_queryset(),
                                     many=True)
        return Response({'results': events.data})

    def create(self, request):
        """POST: save a draft by the requester."""
        if not request.user.has_perm('events.add_event'):
            deny(request, Action.CREATE_EVENT)
        data = EventWriteSerializer(data=request.data)
        data.is_valid(raise_exception=True)
        event = Event(**data.validated_data)
        model_checked(event)
        dry_run = is_dry_run(request)
        event.save_draft(request.user, dry_run=dry_run)
        body = MyEventSerializer(event).data
        if dry_run:
            body['id'] = None
            return Response({'dry_run': True, 'event': body})
        response = Response(body, status.HTTP_201_CREATED)
        response['Location'] = reverse(
            'api:my_event-detail', args=[event.pk])
        return with_tag(response, event)

    def retrieve(self, request, pk):
        """GET one: the event, with its version as ETag."""
        event = self.get_object()
        response = Response(MyEventSerializer(event).data)
        return with_tag(response, event)

    def partial_update(self, request, pk):
        """PATCH: change fields, if the ETag still holds."""
        event = self.get_object()
        version = version_in(request)

        def change(locked):
            """Check the fields sent, and set them on locked."""
            data = EventWriteSerializer(
                locked, data=request.data, partial=True)
            data.is_valid(raise_exception=True)
            for name, value in data.validated_data.items():
                setattr(locked, name, value)
            model_checked(locked)
            return []

        dry_run = is_dry_run(request)
        try:
            edit = event.edit(request.user, version, change,
                              dry_run=dry_run)
        except StaleEdit:
            raise PreconditionFailed from None
        body = MyEventSerializer(edit.event).data
        if dry_run:
            return Response({'dry_run': True, 'event': body,
                             'effects': {
                                 'changed': edit.changed,
                                 'promoted': len(edit.promoted),
                                 'emails': edit.emails}})
        return with_tag(Response(body), edit.event)

    def destroy(self, request, pk):
        """DELETE: remove a draft; anything else refused."""
        event = self.get_object(Action.DELETE_EVENT)
        dry_run = is_dry_run(request)
        event.delete_by(request.user, dry_run=dry_run)
        if dry_run:
            return Response({'dry_run': True,
                             'effects': {'deleted': int(pk)}})
        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(detail=True, methods=['post'])
    def publish(self, request, pk):
        """POST .../publish/: publish a draft that is ready."""
        event = self.get_object(Action.PUBLISH_EVENT)
        dry_run = is_dry_run(request)
        event.publish_by(request.user, dry_run=dry_run)
        return self.answer(event, dry_run, emails=0)

    @action(detail=True, methods=['post'])
    def cancel(self, request, pk):
        """POST .../cancel/: cancel; members are emailed."""
        event = self.get_object(Action.CANCEL_EVENT)
        dry_run = is_dry_run(request)
        queued = event.cancel_by(request.user,
                                 dry_run=dry_run)
        return self.answer(event, dry_run, emails=queued)

    def answer(self, event, dry_run, emails):
        """Answer a publish or a cancel, or its dry run."""
        body = MyEventSerializer(event).data
        if dry_run:
            return Response({'dry_run': True, 'event': body,
                             'effects': {'emails': emails}})
        return with_tag(Response(body), event)

It inherits from GenericViewSet, which has no actions of its own, so the router can route only the seven written here. Each calls the method the site’s page calls. lookup_value_regex makes the router accept only numbers as ids. A DELETE on a published event is refused by delete_by(), with a 422 saying why, which no queryset or permission class could express.

api/urls.py becomes:

"""Addresses of the API, under /api/v1/ (Chapters 47 to 49)."""
from django.urls import path
from rest_framework.routers import SimpleRouter

from . import views

app_name = 'api'
# Chapter 49: the router gives the viewset's actions their
# addresses: my/events/, my/events/{id}/, and .../publish/
# and .../cancel/ for the two @action methods.
router = SimpleRouter()
router.register('my/events', views.MyEventViewSet,
                basename='my_event')

urlpatterns = [
    path('events/', views.event_list, name='event_list'),
    path('events/<int:event_id>/', views.event_detail,
         name='event_detail'),
    *router.urls,
    path('openapi.yaml', views.openapi, name='openapi'),
    # Last: anything else under /api/v1/ is a 404 in JSON,
    # never the site's HTML page.
    path('<path:rest>', views.not_found, name='not_found'),
]

SimpleRouter makes the four addresses of Figure 49.3’s right panel, named my_event-list, my_event-detail, my_event-publish, and my_event-cancel from the basename.

uv run python manage.py test api
Found 58 test(s).
Creating test database for alias 'default'...
...
Ran 58 tests in ...s

OK

Chapter 39’s guard meets its first router:

uv run python manage.py test config.tests.test_public
Found 3 test(s).
Creating test database for alias 'default'...
ERROR: test_a_visitor_is_sent_to_sign_in_elsewhere
django.urls.exceptions.NoReverseMatch: Reverse for
    'my_event-cancel' with no arguments not found. 1
    pattern(s) tried:
    ['api/v1/my/events/(?P<pk>\\d+)/cancel/$']
ERROR: test_a_visitor_is_sent_to_sign_in_elsewhere
django.urls.exceptions.NoReverseMatch: Reverse for
    'my_event-detail' with no arguments not found. 1
    pattern(s) tried: ['api/v1/my/events/(?P<pk>\\d+)/$']
ERROR: test_a_visitor_is_sent_to_sign_in_elsewhere
django.urls.exceptions.NoReverseMatch: Reverse for
    'my_event-publish' with no arguments not found. 1
    pattern(s) tried:
    ['api/v1/my/events/(?P<pk>\\d+)/publish/$']
Ran 3 tests in ...s

FAILED (errors=3)

A router writes its addresses as regular expressions, (?P<pk>\d+), not as <int:pk>, so the guard found no argument to fill in. In config/tests/test_public.py, the lines that build the arguments become:

            # A number for each <int:>, a word for <str:>
            # (Chapter 46's check-in codes); a router's
            # (?P<pk>...) is an event's number (Chapter 49).
            kinds = re.findall(r'<(\w+):', route)
            kinds += ['int'] * route.count('(?P<')
            args = [1 if kind == 'int' else 'x'
                    for kind in kinds]
uv run python manage.py test config.tests.test_public
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

OK

Common Error: a router exposing DELETE nobody intended

What you see: a resource that should never be deleted answers DELETE with 204.

Why it happens: the viewset inherited destroy from ModelViewSet or DestroyModelMixin, and the router routes every action a viewset has.

How to fix it: inherit from GenericViewSet, write only the actions you mean, list the methods in http_method_names, and test that the others answer 405, as test_put_is_not_routed does.

Step 6: The OpenAPI file, from the code

uv add drf-spectacular==0.30.0
Resolved 56 packages in ...
Installed 3 packages in ...
 + drf-spectacular==0.30.0
 + inflection==0.5.1
 + uritemplate==4.2.0

In config/settings.py, the end of INSTALLED_APPS becomes:

    # Chapter 48: Django REST framework; Chapter 49: the
    # OpenAPI file, made from the code.
    'rest_framework',
    'drf_spectacular',
]

in REST_FRAMEWORK, below EXCEPTION_HANDLER:

    # Chapter 49: how each view describes itself.
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',

and at the end of the file:

# The OpenAPI file (Chapter 49): docs/api/openapi.yaml is
# made from the views and serializers by
#   uv run python manage.py spectacular --file ...
# and a test fails if the file and the code disagree.
SPECTACULAR_SETTINGS = {
    'TITLE': 'Otahque API',
    'VERSION': '1.0.0',
    'OAS_VERSION': '3.1.0',
    'DESCRIPTION': (
        "Read Otahque's published and cancelled events; "
        'manage your own events if you organize them. Times '
        "are UTC; show them in each event's timezone. The "
        'rules are in docs/api/contract.md.'),
    'SERVERS': [{'url': '/api/v1'}],
    'SCHEMA_PATH_PREFIX': '/api/v1',
    'SCHEMA_PATH_PREFIX_TRIM': True,
    'SERVE_INCLUDE_SCHEMA': False,
}

drf-spectacular reads types from the code, so the serializers say more. In api/serializers.py, give the computed fields’ methods their return types: get_places_left(self, event) -> int, get_organizers(self, event) -> list[str], get_cover(self, event) -> str | None, and both get_url(self, event) -> str. In EventSerializer.Meta, below fields:

        # Only ever sent, so every field is always there
        # (Chapter 49: the OpenAPI file lists them required).
        read_only_fields = fields

and in MyEventSerializer.Meta, below fields:

        read_only_fields = fields

In EventWriteSerializer, below serializer_field_mapping:

    # Declared, not built from the model: a model's integer
    # gets its database's own limit, which differs between
    # SQLite and PostgreSQL, and so would the OpenAPI file
    # (Chapter 49). The model's rule still checks it.
    capacity = serializers.IntegerField()

and at the end of the file, three serializers that only describe errors:

class ProblemSerializer(serializers.Serializer):
    """A problem-details body, for the OpenAPI file only."""

    type = serializers.CharField()
    title = serializers.CharField()
    status = serializers.IntegerField()
    detail = serializers.CharField()


class FieldErrorSerializer(serializers.Serializer):
    """One item of a 422 problem's errors list."""

    pointer = serializers.CharField(
        help_text='A JSON Pointer, such as #/capacity.')
    detail = serializers.CharField()


class InvalidSerializer(ProblemSerializer):
    """A 422 problem: invalid fields, each one pointed at."""

    errors = FieldErrorSerializer(many=True)

In api/views.py, below the require_safe import:

from drf_spectacular.utils import (
    OpenApiParameter, OpenApiResponse, extend_schema,
    extend_schema_view, inline_serializer,
)

the serializers import gains InvalidSerializer and ProblemSerializer; below Action = AuditEvent.Action:

# Chapter 49: words for the OpenAPI file, which tools and AI
# agents read as the list of what they can do.
PROBLEM = OpenApiResponse(ProblemSerializer,
                          'What went wrong (RFC 9457).')
INVALID = OpenApiResponse(InvalidSerializer,
                          'Invalid fields, each pointed at.')
DRY_RUN = OpenApiParameter(
    'dry_run', bool,
    description='true: check it, report what it would do, '
                'and save nothing.')
IF_MATCH = OpenApiParameter(
    'If-Match', str, OpenApiParameter.HEADER, required=True,
    description='The ETag you read, such as "v3".')

above EventList.get():

    @extend_schema(
        operation_id='listEvents',
        summary='List events that have not ended yet.',
        responses={200: inline_serializer('EventList', {
            'results': EventSerializer(many=True)}),
            405: PROBLEM, 406: PROBLEM})

above EventDetail.get():

    @extend_schema(
        operation_id='getEvent',
        summary='Read one published or cancelled event.',
        responses={200: EventSerializer, 404: PROBLEM,
                   405: PROBLEM, 406: PROBLEM})

above the viewset:

@extend_schema_view(
    list=extend_schema(
        operation_id='listMyEvents',
        summary='List the events you organize, drafts too.',
        responses={200: inline_serializer('MyEventList', {
            'results': MyEventSerializer(many=True)}),
            403: PROBLEM}),
    create=extend_schema(
        operation_id='createDraft',
        summary='Create a draft event that you organize.',
        request=EventWriteSerializer, parameters=[DRY_RUN],
        responses={201: MyEventSerializer, 403: PROBLEM,
                   422: INVALID}),
    retrieve=extend_schema(
        operation_id='getMyEvent',
        summary='Read one of your events; its ETag is its '
                'version.',
        responses={200: MyEventSerializer, 403: PROBLEM,
                   404: PROBLEM}),
    partial_update=extend_schema(
        operation_id='changeMyEvent',
        summary='Change some fields of one of your events.',
        description='Send the ETag you read in If-Match. A '
                    'new timezone needs starts_at and ends_at '
                    'too. A higher capacity gives places to '
                    'waiting members; a new time or place '
                    'emails members holding places.',
        request=EventWriteSerializer,
        parameters=[DRY_RUN, IF_MATCH],
        responses={200: MyEventSerializer, 403: PROBLEM,
                   404: PROBLEM, 412: PROBLEM, 422: INVALID,
                   428: PROBLEM}),
    destroy=extend_schema(
        operation_id='deleteDraft',
        summary='Delete one of your drafts.',
        parameters=[DRY_RUN],
        responses={204: None, 403: PROBLEM, 404: PROBLEM,
                   422: INVALID}),
    publish=extend_schema(
        operation_id='publishMyEvent',
        summary='Publish one of your drafts, if it is ready.',
        request=None, parameters=[DRY_RUN],
        responses={200: MyEventSerializer, 403: PROBLEM,
                   404: PROBLEM, 422: INVALID}),
    cancel=extend_schema(
        operation_id='cancelMyEvent',
        summary='Cancel one of your published events.',
        description='Every member holding a place is '
                    'emailed. Try it with dry_run first.',
        request=None, parameters=[DRY_RUN],
        responses={200: MyEventSerializer, 403: PROBLEM,
                   404: PROBLEM, 422: INVALID}),
)

and the start of get_queryset() becomes:

        """Return the events the requester organizes now.

        While the OpenAPI file is made there is no member,
        so drf-spectacular gets an empty queryset.
        """
        if getattr(self, 'swagger_fake_view', False):
            return Event.objects.none()

extend_schema_view gives each of the viewset’s actions its own description without touching the methods. operation_id is the name a tool or an agent calls the action by; the responses list every status each action can answer.

Now the tests, which change on purpose: the file is no longer written by hand. In api/tests/test_openapi.py, the docstring and imports become:

"""The contract file, and the page that points to it.

docs/api/openapi.yaml was written by hand in Chapters 47
and 48. Since Chapter 49, drf-spectacular makes it from the
views and serializers, and these tests keep it honest: it
must be valid OpenAPI 3.1, the same as the code would make
now, describe every address of the API, and give an Event
exactly the fields the API sends.
"""
import re

from django.conf import settings
from django.test import TestCase
from drf_spectacular.generators import SchemaGenerator
from drf_spectacular.renderers import OpenApiYamlRenderer
from openapi_spec_validator import validate
from openapi_spec_validator.readers import read_from_filename

from api import urls
from api.serializers import WRITABLE, MyEventSerializer

and, in test_write_fields_match_the_api, from mine on:

        mine = schemas['MyEvent']['properties']
        self.assertEqual(set(mine),
                         set(MyEventSerializer.Meta.fields))

    def test_the_file_is_what_the_code_makes(self):
        schema = SchemaGenerator().get_schema(public=True)
        made = OpenApiYamlRenderer().render(schema)
        self.assertEqual(SPEC.read_bytes(), made,
                         'Run: uv run python manage.py '
                         'spectacular --file '
                         'docs/api/openapi.yaml')

    def test_every_address_is_described(self):
        def same(path):
            return re.sub(r'\{\w+\}', '{}', path)

        routes = set()
        for pattern in urls.urlpatterns:
            if getattr(pattern.callback, 'cls', None):
                route = str(pattern.pattern).strip('^$')
                route = re.sub(r'<[^>]+>|\(\?P<\w+>[^)]+\)',
                               '{}', route)
                routes.add('/' + route)
        self.assertEqual({same(p) for p in self.spec['paths']},
                         routes)
uv run python manage.py test api.tests.test_openapi
Found 7 test(s).
Creating test database for alias 'default'...
ERROR: test_write_fields_match_the_api
KeyError: 'properties'
FAIL: test_every_address_is_described
AssertionError: Items in the second set but not the first:
FAIL: test_the_file_is_what_the_code_makes
AssertionError: b'ope[57 chars]0\n  summary: Community
    events, for other prog[10408 chars]ri\n' != b'ope[57
    chars]0\n  description: Read Otahque\'s published
    an[20975 chars]v1\n' : Run: uv run python manage.py
    spectacular --file docs/api/openapi.yaml
Ran 7 tests in ...s

FAILED (failures=2, errors=1)

The file on disk is still Chapter 48’s. Make it from the code:

uv run python manage.py spectacular --file docs/api/openapi.yaml

It prints nothing when it has nothing to warn about; a field whose type it cannot work out would appear here as a warning.

uv run python manage.py test api.tests.test_openapi
Found 7 test(s).
Creating test database for alias 'default'...
...
Ran 7 tests in ...s

OK

From now on, a change to a view or a serializer that changes the API also changes what the code makes, and test_the_file_is_what_the_code_makes fails until you run spectacular again and commit the new file: the change shows up in review as a diff of the contract.

Common Error: the OpenAPI file differs between databases

What you see: the file test passes on SQLite and fails on PostgreSQL, on a maximum of 9223372036854775807 against 2147483647.

Why it happens: a ModelSerializer gives an integer field its database’s own limit, which is 64 bits in SQLite and 32 in PostgreSQL, and the file records it. This chapter’s own checks found it.

How to fix it: declare the field on the serializer, as capacity now is, and leave the range to the model’s rules.

Step 7: The browsable API, in development only

In config/settings.py, above the OpenAPI settings:

# Chapter 49: DRF's browsable pages, an HTML form for each
# address, while developing only. otahque.W005 warns if they
# are on where DEBUG is off.
if DEBUG:
    REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'].append(
        'rest_framework.renderers.BrowsableAPIRenderer')

In config/checks.py, below LOCAL_SITE_URL:

# DRF's HTML pages for each API address (Chapter 49).
BROWSABLE = 'rest_framework.renderers.BrowsableAPIRenderer'

and at the end:

@register('otahque', deploy=True)
def check_browsable_api(app_configs, **kwargs):
    """Warn when DRF's browsable pages are on in production."""
    renderers = settings.REST_FRAMEWORK.get(
        'DEFAULT_RENDERER_CLASSES', [])
    if settings.DEBUG or BROWSABLE not in renderers:
        return []
    return [Warning(
        "DRF's browsable API is on.",
        hint='It shows a form for every address; keep it for '
             'development (config/settings.py, Chapter 49).',
        id='otahque.W005',
    )]

At the end of config/tests/test_checks.py:

class BrowsableCheckTests(SimpleTestCase):
    """otahque.W005: DRF's HTML pages stay in development."""

    JSON = 'rest_framework.renderers.JSONRenderer'

    @override_settings(DEBUG=False, REST_FRAMEWORK={
        'DEFAULT_RENDERER_CLASSES': [JSON, checks.BROWSABLE]})
    def test_browsable_pages_in_production(self):
        self.assertEqual(ids(checks.check_browsable_api(None)),
                         ['otahque.W005'])

    @override_settings(DEBUG=False, REST_FRAMEWORK={
        'DEFAULT_RENDERER_CLASSES': [JSON]})
    def test_json_only_in_production(self):
        self.assertEqual(checks.check_browsable_api(None), [])
uv run python manage.py test config.tests.test_checks
Found 12 test(s).
Creating test database for alias 'default'...
...
Ran 12 tests in ...s

OK

Step 8: Each event’s API address, on My events

Sam’s agent needs the address of the event Sam means. My events shows it. The test, in api/tests/test_mine.py, below the django.test import:

from django.urls import reverse

and at the end:

class MyEventsPageTests(Mine):
    """The site's My events page shows each API address."""

    def test_each_event_has_its_api_address(self):
        self.client.force_login(self.sam)
        page = self.client.get(reverse('events:manage'))
        self.assertContains(
            page, f'<code id="api-{self.event.pk}">'
                  f'{self.address}</code>', html=True)
        self.assertContains(page, 'Copy API address')
uv run python manage.py test api.tests.test_mine
Found 11 test(s).
Creating test database for alias 'default'...
FAIL: test_each_event_has_its_api_address
AssertionError: False is not true : Couldn't find '<code
    id="api-12">/api/v1/my/events/12/</code>' in the
    following response
Ran 11 tests in ...s

FAILED (failures=1)

In events/templates/events/manage.html, below the line that includes when.html:

        {# Chapter 49: where a program finds this event. #}
        {% url 'api:my_event-detail' event.pk as api %}
        <p class="api-address">
          <code id="api-{{ event.pk }}">{{ api }}</code>
          <button type="button" class="btn btn-ghost btn-xs
                  needs-js" data-copy="api-{{ event.pk }}">
            Copy API address</button>
        </p>

At the end of static/otahque/site.js:

// Chapter 49: copy an address, and say so in the live
// region, which screen readers announce. One listener on
// the page also serves buttons htmx swaps in later.
document.addEventListener('click', async (event) => {
  const button = event.target.closest('[data-copy]');
  if (!button) {
    return;
  }
  const source = document.getElementById(
    button.dataset.copy);
  await navigator.clipboard.writeText(
    source.textContent.trim());
  button.textContent = 'Copied';
  document.getElementById('live').textContent =
    'API address copied.';
});

The button has needs-js, so Chapter 45’s rule hides it when the script does not run; the address stays readable either way. One listener on the whole page serves buttons that htmx swaps in later, and the live region from Chapter 45 tells a screen reader that the copy worked. In static/otahque/source.css, above .form-actions:

  /* Chapter 49: an event's API address on My events. */
  .api-address {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.5rem;
    font-size: 0.875rem;
  }
  .api-address code {
    padding: 0.125rem 0.5rem;
    border-radius: var(--radius-field);
    background-color: var(--color-base-200);
    overflow-wrap: anywhere;
  }
npm run build
uv run python manage.py test api.tests.test_mine
Found 11 test(s).
Creating test database for alias 'default'...
...
Ran 11 tests in ...s

OK

Step 9: The records

At the end of docs/adr/ADR-006-views.md:

## Update, Chapter 49: API views

- Context: the API has two kinds of resource. Public
  reads (the event list and one event) answer GET only;
  the organizer's own events answer list, create, read,
  change, publish, cancel, and delete.
- Options compared, against the same tests: APIView with
  hand-written methods; DRF generic views, one per
  address; a ModelViewSet with DefaultRouter.
- Decision (D49.1): public reads stay generic views
  (PublicRead), with http_method_names = ['get', 'head'].
  The organizer's events are one GenericViewSet with only
  the actions the contract lists, routed by SimpleRouter:
  no PUT, no format-suffix addresses, no API root, and
  DELETE only through delete_by(), which refuses anything
  but a draft. Each action calls the model method the
  site's page calls (Chapters 48 and 49).
- Not chosen: ModelViewSet with DefaultRouter. With no
  more than the project's defaults, it let a signed-in
  member who organizes nothing delete a published event
  (204), answered PUT, and added addresses nobody planned:
  format suffixes (.json) and an API root.
- Rule: every API view states its methods; a router only
  routes actions a viewset defines.
- Revisit: if the API grows to many resources with the
  same actions, where a ModelViewSet's defaults fit.

In docs/api/contract.md, the opening’s last sentence becomes:

The machine-readable copy is `docs/api/openapi.yaml`,
made from the code since Chapter 49:
`uv run python manage.py spectacular --file
docs/api/openapi.yaml`.

in the organizer’s section, the first paragraph ends:

session since Chapter 48, with a token from Chapter 50.
Members who organize nothing get 403 from the list.

and the dry-run bullet ends:

  "promoted": 1, "emails": 3}}` (a new draft has no
  effects, and its `id` is null). Publish and cancel
  report `{"emails": n}`, the members a cancel tells;
  DELETE reports `{"deleted": id}`.
- Publish refuses a draft that is not ready, and DELETE
  anything but a draft, with 422 and the reasons.

Step 10: In a browser

Run the server and open http://127.0.0.1:8000/api/v1/events/. With DEBUG on, DRF answers a browser with its browsable page. Then sign in as an organizer, open My events, and press Copy API address. Figure 49.4 shows both.

Two screenshots. Left, My events on a phone, 390 pixels wide: a card for Summary clinic, marked Published, with its date, then the address /api/v1/my/events/13/ in a grey box beside a small button that now reads Copied, and the Edit and Copy links below. Right, at 1280 pixels, DRF’s browsable page for GET /api/v1/events/: the title Event List, the request line, the response headers (HTTP 200 OK, Allow: GET, HEAD, Cache-Control: no-cache, Content-Type: application/json), and the JSON list with one event.
Figure 49.4 — My events, and DRF’s browsable page while developing.

Step 11: The checks, and the commit

uv run python check.py
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
== python manage.py test --parallel
Found 685 test(s).
System check identified no issues (0 silenced).
Ran 685 tests in ...s
OK
== all checks passed
git add .
git status --short
git commit -m "Organize the API in a viewset; generate OpenAPI"
M  api/serializers.py
A  api/tests/test_mine.py
M  api/tests/test_openapi.py
M  api/urls.py
M  api/views.py
M  config/checks.py
M  config/settings.py
M  config/tests/test_checks.py
M  config/tests/test_public.py
M  docs/adr/ADR-006-views.md
M  docs/api/contract.md
M  docs/api/openapi.yaml
M  events/models.py
M  events/templates/events/manage.html
M  events/views.py
M  pyproject.toml
M  static/otahque/site.css
M  static/otahque/site.js
M  static/otahque/source.css
M  uv.lock
[main 1a2b3c4] Organize the API in a viewset; generate
    OpenAPI
 20 files changed, 1259 insertions(+), 274 deletions(-)
 create mode 100644 api/tests/test_mine.py

If something goes wrong

Table 49.2 — Recovery for Chapter 49
What you see Likely cause What to do
NoReverseMatch for my_event The old names my_events and my_event Use my_event-list, my_event-detail, and the action names
405 on PATCH partial_update missing, or patch not in http_method_names Define the action and list the method
PUT answers 200 The viewset inherited update() Inherit GenericViewSet; leave PUT out of http_method_names
test_the_file_is_what_the_code_makes fails The code changed the API Run spectacular --file, read the diff, and commit it
spectacular warns it cannot resolve a type A SerializerMethodField without a return type Add -> int, -> str, or the right type
AttributeError on request.user while making the file get_queryset() reads the user Return none() when swagger_fake_view is set
The Copy button is missing The script did not run, or the stylesheet is old Check the browser's console; run npm run build
otahque.W005 on check --deploy The browsable renderer is on with DEBUG off Keep it inside if DEBUG
PAGE 003

Verify Your Work

Work through Table 49.3 from the folder that holds manage.py, with Otahque on PostgreSQL.

Table 49.3 — Verification checklist for Chapter 49
Check Command or action Expected result
Starting point test --parallel Found 670 test(s); OK
Three ways ways.py in the shell Six router addresses; a member deletes a published event: 204
One path test events registrations OK, unchanged
The viewset test api Red first; then 58 tests OK
Chapter 39's guard test config.tests.test_public Red on purpose; then 3 tests OK
The OpenAPI file test api.tests.test_openapi; spectacular --file Red until the file is made; then 7 tests OK
Development only test config.tests.test_checks OK, with otahque.W005
My events test api.tests.test_mine One failure first; then 11 tests OK
In a browser /api/v1/events/; My events, Copy, at 390 and 1280 px The browsable page; the clipboard holds the address
All checks uv run python check.py == all checks passed; Ran 685 tests
Commit git log --oneline -1 Organize the API in a viewset; generate OpenAPI
Not verified A real agent reading the OpenAPI file; macOS and Linux shells Read the file yourself, as an agent would

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 48 checkpoint with a reader’s data, against PostgreSQL 18; commands that write files ran once. In Microsoft Edge, at 390 and 1280 pixels, a Playwright script opened /api/v1/events/ and found DRF’s browsable page, then, signed in as Sam, opened My events, pressed Copy API address, and read the clipboard back: it held the event’s address, the button said Copied, and the live region spoke. One sample event was added for it and deleted afterwards.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 1 What did ways.py show about ModelViewSet with Otahque’s own defaults?

Flip to check your answerFold answer back

Answer. A signed-in member who organizes nothing could delete a published event: the default permission only asks that someone is signed in, and the queryset was every event. The router also made addresses nobody asked for.

Que. 2 Why does Otahque’s viewset inherit from GenericViewSet, not ModelViewSet?

Flip to check your answerFold answer back

Answer. GenericViewSet has no actions of its own, so the router routes only the seven the contract lists, each written to call the model’s method. Nothing extra appears by inheritance.

Que. 3 What is the difference between DefaultRouter and SimpleRouter?

Flip to check your answerFold answer back

Answer. DefaultRouter also makes format-suffix addresses (.json) and an API root page; SimpleRouter makes only the list, detail, and @action addresses.

Que. 4 How can a test know the OpenAPI file is out of date?

Flip to check your answerFold answer back

Answer. It makes the file from the code, with drf-spectacular’s generator, and compares the result with the file on disk, byte for byte.

Que. 5 Why is the browsable API guarded by a deploy check as well as if DEBUG?

Flip to check your answerFold answer back

Answer. The setting keeps it out of production today; the check warns if a later change turns it on anyway, at the moment a release runs check --deploy.

Mini-Challenge

DefaultRouter would make my/events/7.json. Otahque’s SimpleRouter should not. Write a test, in api/tests/test_no_suffix.py, that checks such an address is not found, and answers as a problem.

Hint: Mine in test_mine.py signs Sam in and sets self.address.

Model answer:

"""Mini-Challenge: no .json addresses on my events."""
from api.tests.test_mine import Mine


class NoSuffixTests(Mine):
    """SimpleRouter() makes no format-suffix addresses."""

    def test_a_json_suffix_is_not_an_address(self):
        page = self.api.get(f'{self.address[:-1]}.json')
        self.assertEqual(page.status_code, 404)
        self.assertEqual(page['Content-Type'],
                         'application/problem+json')
uv run python manage.py test api.tests.test_no_suffix
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

The model answer was run and then removed; the chapter’s checkpoint does not include it.

What We Learned

  • DRF’s layers run in a fixed order: the router or URL, authentication, permissions, the action, the serializer, the response; every error goes to one handler.
  • APIView, generic views, and viewsets differ in how much they assume; the more they assume, the more they do that nobody decided.
  • A router routes every action a viewset has; write only the actions you mean, and list the methods.
  • Custom actions such as publish and cancel are @action methods with their own addresses.
  • Publish, cancel, and delete go through the same model methods for the page and the API, as edits do.
  • An OpenAPI file made from the code, with a test comparing them, cannot drift.
  • Development tools stay in development, with a check that says so.

Key terms

Use Table 49.4 to explain this chapter’s ideas in your own words.

Table 49.4 — Key terms from Chapter 49
Term Meaning
APIView DRF's base view: one method per HTTP verb.
Generic view A view whose actions come from mixins.
ViewSet One class with every action on a resource.
Action A viewset's method: list, retrieve, @action.
Router Makes URL patterns from a viewset's actions.
Format suffix An address ending in .json; DefaultRouter's extra.
drf-spectacular Makes an OpenAPI file from DRF's code.
operationId The name a tool calls an operation by.
Browsable API DRF's HTML page for each address.
Deploy check A system check that runs on check --deploy.

Readiness checkpoint: you are ready for Chapter 50 when uv run python check.py ends with “all checks passed” and 685 tests, docs/api/openapi.yaml is the file the code makes, My events copies an event’s API address, and git log --oneline -1 shows this chapter’s commit.

Git Commit

Your Chapter 49 work was committed once, in Step 11, as “Organize the API in a viewset; generate OpenAPI”: the settings and checks, the serializers, views, and addresses, the events models and views, the generated OpenAPI file, the My events template, the script, the stylesheet and its compiled CSS, pyproject.toml and uv.lock, the contract, ADR-006, the new test module, and the three changed ones. If you kept the Mini-Challenge, commit it on its own:

git add api/tests/test_no_suffix.py
git commit -m "Check there are no .json addresses"
PAGE 005

Test Your Knowledge: Interview Questions

These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead, to a 405 that surprises a client and to when a team should choose viewsets. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.

L1 (Junior): APIView, generic view, or viewset: what is the difference?

What the interviewer is testing: Can you place the three styles on one scale?

Flip to check your answerFold answer back

Perfect answer: They differ in how much they write for you. An APIView has a method per HTTP verb and assumes nothing. A generic view adds a queryset, a serializer, and actions from mixins, one view per address. A viewset holds every action on a resource, named by what it does, and a router gives them addresses. More assumed means less code and more that happens without a decision: ways.py showed a generic view answering PUT and a ModelViewSet letting a member delete an event. Otahque uses generic views for its two public reads and a viewset with only the contract’s actions for the organizer’s events.

Table 49.5 — The three styles in Otahque
Style Where Why
APIView Not used Too much by hand for the same result
Generic view The public reads One address, one job
GenericViewSet My events Seven actions on one resource

Behind the scenes:

ByHand   GET, OPTIONS
Generic  GET, PUT, PATCH, DELETE, OPTIONS

Code proof: the viewset’s tests:

Found 11 test(s).
Creating test database for alias 'default'...
...
Ran 11 tests in ...s

OK

Common mistakes:

  • Choosing the biggest abstraction because a tutorial used it.
  • Thinking a viewset is a different kind of view; as_view() still makes one Django view per address.

Follow-up the interviewer might ask:

  • When would an APIView be right? (For an endpoint that is not a resource at all, such as a health check.)

L2 (Mid-Level): Predict the addresses a router makes for Otahque’s viewset

What the interviewer is testing: Can you read what a router will expose before it is deployed?

Flip to check your answerFold answer back

Perfect answer: A router makes a list address for list and create, a detail address for retrieve, partial_update, and destroy, and one address per @action with detail=True: my/events/, my/events/{id}/, my/events/{id}/publish/, and my/events/{id}/cancel/. That is what SimpleRouter makes. DefaultRouter makes each of those twice, once with a .json suffix, plus an API root and its own suffix twin: nine addresses for four meant. Each address answers only the methods the viewset’s actions and http_method_names allow.

A numbered flow of five cards. 1, the viewset: list, create, retrieve, partial_update, destroy, publish, cancel. 2, list and create: my/events/. 3, the rest: my/events/{id}/. 4, @action: .../publish/ and .../cancel/. 5, DefaultRouter adds .json twins and an API root.
Figure 49.5 — From actions to addresses.

Behind the scenes:

list, create     GET POST my/events/
retrieve         GET      my/events/{id}/
partial_update   PATCH    my/events/{id}/
destroy          DELETE   my/events/{id}/
publish, cancel  POST     my/events/{id}/<action>/

Code proof: both routers, for the same viewset:

"""The addresses two routers make for the same viewset."""
from rest_framework.routers import DefaultRouter, SimpleRouter

from api.views import MyEventViewSet

for router in (DefaultRouter(), SimpleRouter()):
    router.register('my/events', MyEventViewSet,
                    basename='try')
    print(type(router).__name__)
    for url in router.urls:
        print('  ', url.pattern, url.name)
DefaultRouter
   ^my/events/$ try-list
   ^my/events\.(?P<format>[a-z0-9]+)/?$ try-list
   ^my/events/(?P<pk>\d+)/$ try-detail
   ^my/events/(?P<pk>\d+)\.(?P<format>[a-z0-9]+)/?$
    try-detail
   ^my/events/(?P<pk>\d+)/cancel/$ try-cancel
   ^my/events/(?P<pk>\d+)/cancel\.(?P<format>[a-z0-9]+)/?$
    try-cancel
   ^my/events/(?P<pk>\d+)/publish/$ try-publish
   ^my/events/(?P<pk>\d+)/publish\.(?P<format>[a-z0-9]+)/?$
    try-publish
    api-root
   <drf_format_suffix:format> api-root
SimpleRouter
   ^my/events/$ try-list
   ^my/events/(?P<pk>\d+)/$ try-detail
   ^my/events/(?P<pk>\d+)/cancel/$ try-cancel
   ^my/events/(?P<pk>\d+)/publish/$ try-publish

Common mistakes:

  • Forgetting the format-suffix addresses when listing what a site exposes.
  • Assuming a router adds only the actions you used, not the ones the viewset inherited.

Follow-up the interviewer might ask:

  • How would you list every address a project answers? (Walk the URL resolver, as Chapter 39’s guard does, and the OpenAPI file for the API.)

L3 (Senior): Defend writing the viewset’s actions instead of using mixins

What the interviewer is testing: Can you trade convenience for control, and say when?

Flip to check your answerFold answer back

Perfect answer: DRF’s mixins write the usual actions for you, by saving and deleting through the serializer and the queryset. Otahque’s actions each must call a model method instead: edit() for a change, save_draft(), publish_by(), cancel_by(), delete_by(), so the API keeps the site’s locks, records, emails, and rules, such as “only a draft can be deleted”. A mixin’s destroy() would call delete() and skip all of that. So the viewset inherits GenericViewSet, which gives the shared parts (get_serializer, kwargs, the router’s actions) and no actions; each action is a few lines calling the model. The cost is code a mixin would have given; the gain is that every action does exactly what the page does, and nothing else can be routed.

A numbered flow of five cards. 1, need: every action as the site does it. 2, a mixin saves through the serializer. 3, Otahque’s rules live in model methods. 4, GenericViewSet: shared parts, no actions. 5, each action calls the model; nothing else is routed.
Figure 49.6 — Writing the actions.

Behind the scenes:

create            Event.save_draft()
partial_update    Event.edit()
publish           Event.publish_by()
cancel            Event.cancel_by()
destroy           Event.delete_by()

Code proof: the actions, against the site’s rules:

Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s

OK

Common mistakes:

  • Overriding perform_destroy() in a ModelViewSet and forgetting update() is still routed.
  • Putting the “only drafts” rule in a permission class, where the page cannot use it.

Follow-up the interviewer might ask:

  • When would mixins be right? (For a resource whose saves have no side effects, such as a member’s saved filter.)

L4 (Senior): A client gets 405 for PUT on its event. Diagnose it

What the interviewer is testing: Can you tell a design decision from a bug, from the response alone?

Flip to check your answerFold answer back

Perfect answer: 405 means the address exists and the method does not, and the Allow header lists the methods that do: here GET, HEAD, PATCH, DELETE. So nothing is broken: the contract has no PUT, because PUT replaces the whole resource and Otahque’s writes change some fields under If-Match. The fix is in the client: send PATCH with only the fields it changes. Had the header listed PUT, the cause would be a viewset whose http_method_names and actions disagree. The OpenAPI file says the same as Allow, which is why a client generated from it never sends PUT.

A numbered flow of five cards. 1, symptom: PUT answers 405. 2, read Allow: GET, HEAD, PATCH, DELETE. 3, the contract has PATCH, not PUT. 4, fix the client: PATCH the changed fields, with If-Match. 5, the OpenAPI file lists no PUT either.
Figure 49.7 — Diagnosing a 405.

Behind the scenes:

405 Method Not Allowed
Allow: GET, HEAD, PATCH, DELETE
{"type": "about:blank", "detail": "PUT is not allowed here."}

Code proof: PUT on one of Sam’s events, made and rolled back:

"""What one of my events answers to PUT, and why."""
from datetime import timedelta

from django.db import transaction
from django.test import Client
from django.utils import timezone

from accounts.models import User
from events.models import Event

sam = User.objects.get(email='sam@example.org')
start = timezone.now() + timedelta(days=30)
with transaction.atomic():
    event = Event.objects.create(
        title='Clinic', starts_at=start,
        ends_at=start + timedelta(hours=2),
        timezone='Europe/London', location='Leeds',
        capacity=10)
    event.add_organizer(sam)
    client = Client(HTTP_HOST='localhost')
    client.force_login(sam)
    answer = client.put(f'/api/v1/my/events/{event.pk}/',
                        '{}', content_type='application/json')
    print('PUT:', answer.status_code)
    print('Allow:', answer['Allow'])
    transaction.set_rollback(True)
PUT: 405
Allow: GET, HEAD, PATCH, DELETE

Common mistakes:

  • Adding PUT to make the client work, without its own rules for missing fields.
  • Ignoring Allow, which answers the question directly.

Follow-up the interviewer might ask:

  • What should a 405 for PATCH tell you? (That the viewset lost partial_update or 'patch': a real bug, which test_put_is_not_routed’s Allow check would catch.)

L5 (Lead): When would a team move to viewsets everywhere?

What the interviewer is testing: Can you set a rule with its revisit point, not just a preference?

Flip to check your answerFold answer back

Perfect answer: Viewsets pay off when many resources have the same actions and the same rules, so one pattern covers each new resource. Otahque has one resource with many actions and two public reads with one each, so it uses a viewset where it fits and generic views elsewhere, written down in ADR-006 with the rule that every view states its methods. I would move more to viewsets when the API grows to several resources with the usual actions, and I would keep the safety that matters whatever the style: no inherited actions, SimpleRouter, explicit methods, and the generated OpenAPI file with its drift test, so every new address appears in review as a change to the contract.

A numbered flow of five cards. 1, need: the next endpoint written the same way. 2, viewsets fit many resources with the usual actions. 3, Otahque: one viewset, two generic views, ADR-006. 4, kept whatever the style: explicit actions and methods, SimpleRouter. 5, the OpenAPI drift test shows every new address.
Figure 49.8 — Choosing a view style for a team.

Behind the scenes:

public reads   generic views, GET and HEAD
my events      GenericViewSet, 7 actions
rule           every view states its methods
revisit        many resources, same actions

Code proof: the OpenAPI tests, including every address described:

Found 7 test(s).
Creating test database for alias 'default'...
...
Ran 7 tests in ...s

OK

Common mistakes:

  • Mixing styles without a written rule, so each endpoint is a new argument.
  • Measuring a style by lines of code instead of by what it exposes.

Follow-up the interviewer might ask:

  • How do tokens in Chapter 50 change the viewset? (Its permission classes check the token’s scope per action: read for list and retrieve, write for create and change, publish for publish and cancel, delete for destroy.)

Next: Chapter 50, API authentication and permissions, gives programs and agents tokens of their own, limited by scopes, so Sam’s script can work without his session.

PAGE 006