ContentsClose contents
Pre-release
Chapter 47 · API design and HTTP contractsCHAPTER 47

Complete six-part pre-release for review. Opens Stage 6 and Milestone 4. Two packages: django-cors-headers and, for tests, openapi-spec-validator. The public ETag is a hash of the answer, because the event's version misses publishing, places, and organizers. A real-browser check found the If-None-Match preflight problem that the unit tests missed.

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-SEVEN

API design and HTTP contracts

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

Prerequisites: Chapters 9 to 46, including the Chapter 46 project with its 620 passing tests, sign-in by default with login_not_required (Chapter 39), the event’s places left and organizers (Chapters 31 and 42), SITE_URL (Chapter 43), and the event’s version (Chapter 33)

What you’ll build: a written contract for Otahque’s first API; a machine-readable copy of it in OpenAPI 3.1, checked by a validator; two endpoints, the event list and one event, written by hand with JsonResponse; errors as problem details; ETags and 304 Not Modified; browser access for partner sites, limited to the public reads; and a page for developers

Why This Matters

The Delhi library has a website with a “What’s on” box, and it wants Otahque’s community events in it. A student club wants the same events in its calendar app. Sam has a different wish: he keeps his clinic’s details in a script, and the AI agent he works with drafts his event descriptions; he would like both to update Otahque directly.

Each of them could read Otahque’s pages and pick the facts out of the HTML. It works for a week, until a designer moves the date into a new box, and the library’s “What’s on” shows nothing. People read pages; programs need something firmer: an API (application programming interface), a set of addresses that answer in a format a program reads, with promises about what each answer holds and how it may change.

Those promises are the important part. Which addresses exist? Which fields does an event have, and in which time zone? What does a draft’s id return? How does an error look? When may a program reuse what it read last time? What will never change without warning? Written down, the answers are a contract: the library’s developer builds against it, and Otahque’s developers keep it.

This chapter writes Otahque’s contract first, then builds its reading half by hand with plain Django views, so you see every piece Django REST framework will do for us in Chapter 48. The writing half, for Sam’s script and his agent, is in the contract from the start, and arrives in Chapters 48 to 50.

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

  • write an API contract: who it serves, its addresses, its fields, its errors, its caching, and its compatibility promise;
  • tell a resource from its representation, and choose what a representation leaves out;
  • use HTTP’s methods and status codes as they are defined, including 404, 405, and 406;
  • send errors as problem details (RFC 9457) instead of HTML pages;
  • give an answer an ETag that changes whenever the answer does, and answer 304 Not Modified;
  • describe an API in OpenAPI 3.1, and test that the description and the API agree;
  • let browsers on other sites read public data, and nothing else, with CORS.

Out of scope: Django REST framework (Chapter 48), writes and their validation (Chapters 48 and 49), tokens and permissions for programs (Chapter 50), paging, filtering, and rate limits (Chapter 51), and webhooks (Chapter 52).

PAGE 001

What You Need to Know

An API is a contract

New Concept: an API contract

What problem exists? A program that reads Otahque breaks whenever Otahque changes something it relied on, and nobody can tell in advance what that is.

What did people do before? Read pages and picked facts out of the HTML (“scraping”), or emailed spreadsheets.

What is it? An API contract is a document that says, for each address: which methods it answers, what each answer holds, which errors it gives and how they look, and what may change later. Both sides build against it: the client trusts it, the server tests itself against it.

Why use it? It turns “whatever the code does today” into promises you can test, and a breaking change into a decision instead of an accident.

Now let’s use it. Step 2 writes Otahque’s as docs/api/contract.md, before any code.

Who reads Otahque’s API decides what goes in it. Table 47.1 names them, as decided for this chapter (D47.1).

Table 47.1 — Who the API serves
Client What it does How it signs in
A partner's website Reads published events Not at all: public
A calendar app Reads published events Not at all: public
Sam's script or AI agent Creates and changes his own events With a token (Chapter 50)
A member Registers on the site, not through the API (no API access)

An AI agent is the newest kind of client, and the easiest to misjudge. An agent that holds Sam’s token is a program acting for Sam: it can do what Sam can do on the site, and nothing more. Everything that protects Otahque from a careless script protects it from a careless agent too: a clear contract, errors it can read, and rules the server enforces whatever the client believes. Chapters 48 to 50 add the rest an agent needs: a way to ask what a change would do before making it, and a token limited to the actions it was given.

Resources and representations

An API’s addresses name resources: “the list of upcoming events”, “event 7”. What a client receives is a representation of the resource: a document, here in JSON, that shows some of its facts in a chosen form. The representation is not the model. Figure 47.1 shows the difference for an event.

Two panels. In the database: three green cards, Event (title, times, timezone, capacity, status, version, phone_required, reminders, check-in window, cover file), Registrations (members, their emails, phones, and answers), and Organizer assignments (members, current or revoked). Arrows lead to In the API: Copied (id, title, description, location, capacity, timezone), Converted (times in UTC ending in Z; status published or cancelled), and Computed (places_left; organizers’ names; the cover and the page as full addresses). Below both, a red card: Never leaves: members’ emails, phones, and answers; the version; drafts.
Figure 47.1 — An event, in the database and in the API.

Three choices made the right column. Times are UTC instants, ending in Z, with the venue’s zone named beside them, so a client in any zone can show the right local time and never has to guess. Some fields are computed: places_left from the registrations, organizers from the current assignments, the addresses in full from SITE_URL. And much is left out on purpose: no member’s email, phone, or answers (Chapter 31’s rule), no version, which is an internal counter, and no drafts at all.

HTTP says most of it already

HTTP, the protocol under every web page, already defines what methods mean and what status codes say. An API that uses them as defined (RFC 9110) needs fewer words of its own. Table 47.2 shows the methods Otahque’s contract uses.

Table 47.2 — Methods in Otahque’s contract
Method Means Safe Idempotent
GET Send me a representation Yes Yes
HEAD The headers of a GET, no body Yes Yes
POST Process this: create, or an action No No
PATCH Change these fields No No
DELETE Remove it No Yes

A safe method changes nothing on the server, so a browser, a crawler, or a link preview may send it freely. An idempotent method has the same effect sent once or ten times, so a client may resend it after a timeout. That is why Chapter 46’s scan page changes nothing on GET, and why the reading endpoints in this chapter answer only GET and HEAD.

Status codes are the first thing a program reads. This chapter’s endpoints use five: 200 OK, 304 Not Modified, 404 Not Found, 405 Method Not Allowed (with an Allow header listing the methods that work), and 406 Not Acceptable, when the client’s Accept header rules out JSON. Asking for a format with Accept, and getting it or a 406, is content negotiation.

Errors a program can read

When Django cannot find a page, it sends the site’s 404 page: HTML, made for people. A program that asked for JSON gets markup it cannot read, and has to guess from the status code alone.

New Concept: problem details

What problem exists? Every API used to invent its own error shape, {"error": ...} here and {"message": ...} there, so every client wrote new error handling for every API.

What did people do before? Exactly that, or sent the status code alone.

What is it? Problem details is an Internet standard, RFC 9457 (2023, replacing RFC 7807): a JSON object with the media type application/problem+json and members type (a URI naming the kind of problem; about:blank means “just the status code”), title (a short summary of that kind), status, detail (what happened this time), and optionally instance. An API may add members of its own; clients ignore those they do not know.

Why use it? One shape for every error, from every endpoint, that generic tools already understand.

Now let’s use it. Step 5 writes api/problems.py, one function that every error goes through.

Otahque’s 404 looks like this:

{"type": "about:blank", "title": "Not Found",
 "status": 404,
 "detail": "No published event has this id."}

A program reads status and type; detail is for the person debugging, and may change. Chapter 48 adds a list of field errors for writes, in the shape RFC 9457’s own example uses.

Answers a client may keep

The library’s site shows the same ten events to every visitor. Asking Otahque for all of them, every time, wastes both sides’ work when nothing has changed. HTTP’s answer is a validator: a tag the server puts on each answer, and the client sends back next time.

Under the Hood: ETags and conditional requests

An ETag is an opaque string, in quotes, that the server sends with a representation: ETag: "3f9a...". Next time, the client sends it back in If-None-Match. If the representation the server would send now has the same tag, it answers 304 Not Modified with no body, and the client uses its copy. RFC 9110 calls a tag strong when it “changes value whenever a change occurs to the representation data”, and that is the rule that matters: a tag that stays the same while the answer changes makes clients show stale data, silently. The same tag also protects writes: a client sends If-Match with the tag it read, and the server refuses the change with 412 Precondition Failed if the resource has changed since. Chapter 48 uses that.

The plan for this chapter first proposed the event’s version as its tag. Chapter 33 added version to stop two organizers overwriting each other, and it counts edits made through the edit page and the admin. But the public representation changes in other ways too, and Table 47.3 shows what version misses.

Table 47.3 — What changes the public answer, and what changes version
Change version The answer
An organizer edits the title +1 Changes
Publishing or cancelling Same Changes (status)
Sai registers Same Changes (places_left)
Raj becomes an organizer Same Changes (organizers)

A partner holding a version tag would be told “Not Modified” for an event that has since been cancelled. So the public reads use a tag made from the answer itself: a hash of the JSON body, which changes whenever any byte does (N47.7). Django already has the pieces: ConditionalGetMiddleware hashes a response’s body into an ETag and answers 304, and decorator_from_middleware() turns it into a decorator for the two views that need it. Figure 47.2 shows the exchange.

Five numbered cards in order. 1, GET /api/v1/events/7/: Otahque answers 200 with the event and ETag “3f9a”. 2, the partner keeps its copy and the tag. 3, GET again with If-None-Match “3f9a”: Otahque builds the answer again and hashes it. 4, same hash: 304 Not Modified, no body. 5, Sai registers: places_left changes, so the hash does, and the next request gets 200 and a new tag.
Figure 47.2 — A conditional GET.

The organizer’s own view of an event, from Chapter 48, is different: its fields change only through edits, so there version is exactly right, and an organizer’s PATCH is refused with 412 when it is stale.

There is no Last-Modified header either, the other validator HTTP offers: Otahque does not record when an event last changed, and a tag from the body already covers every change.

Browsers on other sites

The library’s “What’s on” box may fetch events from the visitor’s browser, with a few lines of JavaScript on the library’s own page. Browsers forbid that by default: a page from one origin (scheme, host, and port, such as https://library.example) may send a request to another origin, but may not read the answer, unless that other origin says it may. That rule, the same-origin policy, is what stops any site you visit from reading your Otahque pages with your cookies.

New Tool: django-cors-headers

What problem exists? Some of Otahque’s data should be readable from other sites’ pages, and the rest never.

What did people do before? Ran every partner request through the partner’s own server, or used workarounds such as JSONP that gave up the browser’s protection.

What is it? CORS (Cross-Origin Resource Sharing) is the standard way for a server to say who may read its answers: headers such as Access-Control-Allow-Origin: *. For requests beyond simple reads, the browser first sends an OPTIONS preflight asking which methods and headers are allowed. django-cors-headers is a maintained package that adds those headers from settings. Version 4.9.0 lists Django 6.0 as its newest tested release; it was checked on Django 6.1.2 for this chapter, and its support is checked again at the Django 6.2 upgrade.

Why use it? A few settings instead of headers written by hand, with a regular expression that limits it to the addresses meant to be public.

Now let’s use it. Step 8 allows any site to read the public addresses, without cookies, and no other address.

The setting that matters most is the one that limits it. Organizer addresses, from Chapter 48 on, send no CORS headers at all, so no other site’s page can use a signed-in organizer’s browser to change events.

A contract a machine can read

contract.md is for people. Programs, code generators, testing tools, and AI agents read a machine-readable form.

New Tool: OpenAPI, and openapi-spec-validator

What problem exists? A contract in prose cannot be checked by a program, and drifts from the code without anyone noticing.

What did people do before? Wrote documentation by hand, and found out it was wrong from users.

What is it? OpenAPI is a standard format, in YAML or JSON, for describing an HTTP API: its paths, methods, parameters, response bodies (as JSON Schema), and errors. Version 3.1 is current. openapi-spec-validator (0.9.0) checks that a file follows the OpenAPI rules. It is a development dependency: the tests need it, the running site does not.

Why use it? Tools read it: they draw documentation, generate clients, and, for an AI agent, describe each operation as a tool it can call. And a test can compare it with what the API really sends.

Now let’s use it. Step 7 writes docs/api/openapi.yaml by hand, validates it, and checks its fields against the API’s. Chapter 49 generates it from the code instead, and compares the two.

Promises about change

The last part of the contract is about the future. Otahque’s rule (D47.2): every address starts with /api/v1/, and within version 1, fields and addresses are only ever added, never renamed, retyped, or removed. Clients must ignore fields they do not know, so adding one breaks nobody. A change that would break a program gets /api/v2/, and version 1 keeps working for at least six months after it. A version in the path is the easiest kind to see, to test, and to document; Table 47.4 compares it with the alternatives.

Table 47.4 — Where an API’s version can go
Where Example Trade-off
In the path (Otahque) /api/v1/events/ Visible everywhere; a new version is new addresses
In a header Accept: application/vnd.otahque.v1+json Clean addresses; easy to forget, hard to see in logs
None /api/events/ Simple until the first breaking change

In practice: the same endpoint in another framework

Situation. Django REST framework is the usual choice for Django APIs, and Otahque uses it from Chapter 48. Django Ninja (1.8.0, for Django 6.1) is the other well-known one.

Application. In Ninja, the list endpoint is a function with a type-annotated return value, a Pydantic schema listing the fields; Ninja turns it into JSON and into OpenAPI automatically, much as FastAPI does. In DRF, the same fields live in a serializer, a class that works like the ModelForms you already know, with a browsable page for each endpoint.

Consideration. Compare them by what they give you, not by speed: DRF’s serializers mirror forms and validate writes the way the edit page does, and it is the one most Django projects and jobs use, so Otahque uses DRF (N47.6). Chapter 75 returns to Ninja and other alternatives.

PAGE 002

How We Build It

Start from Chapter 46, in the folder containing manage.py, with Otahque on PostgreSQL 18, 620 passing tests, and the work committed (the last commit is “Add waitlists and check-in”). Two packages are added: django-cors-headers 4.9.0, and, for the tests only, openapi-spec-validator 0.9.0. There is no new model and no migration. The new files are the contract and its OpenAPI copy in docs/api/, a new app, api, with its problem helper, its representation, its views, its addresses, a template for the developers page, and five test modules. The settings, the project’s addresses, the footer, the stylesheet, pyproject.toml, and Chapter 39’s route test change. The visible result: /api/v1/events/ and /api/v1/events/7/ answer in JSON, errors are problem details, an unchanged answer costs a 304, a partner’s page on another site can read the events, and every page’s footer links to a page for developers. The commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.

The Custom Way

Before any framework, an API is a view that returns JSON instead of HTML, and Django has had one for that since its early days: JsonResponse. This chapter is the Custom Way, on purpose. Every view, every error, every header is written by hand, so that when Chapter 48 replaces these views with Django REST framework, you know what each of its pieces does, and the tests written here prove it does the same.

The Django Way

The Django Way, for now, is to use what Django already gives: JsonResponse and its encoder for dates, request.accepts() for content negotiation, login_not_required from Chapter 39, and ConditionalGetMiddleware for ETags. Chapter 48 adds the framework.

Step 1: Check the starting point

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

OK
git status --short
git log --oneline -1
... Add waitlists and check-in

Step 2: Write the contract

Before any code, the promises. Create the folder docs/api/ and in it contract.md:

# Otahque API contract, version 1

Chapter 47. What Otahque promises programs that read its
events, and, later, organizers' programs that change them.
The machine-readable copy is `docs/api/openapi.yaml`.

## Who it serves

- Partner sites and calendars: read published and
  cancelled events, signed out, from a server or from a
  page's script on another site.
- Organizers' programs, by a person or an AI agent acting
  for them: create, change, publish, cancel, and delete
  their own events, with a token, never more than the
  organizer may do on the site (Chapters 48 to 50).
- Not served: members registering through the API; member
  or attendee data of any kind.

## Addresses

Every address starts with `/api/v1/` and ends with `/`.

| Method | Address | Answer |
|---|---|---|
| GET | `/api/v1/events/` | Events not yet ended |
| GET | `/api/v1/events/{id}/` | One event |
| GET | `/api/v1/openapi.yaml` | This contract, in OpenAPI |

The list holds published and cancelled events whose end
is still to come, soonest start first, as `{"results":
[...]}`. Until paging arrives (Chapter 51), it holds them
all. A draft is never listed, and its id answers 404, the
same as an id that does not exist.

## An event

| Field | Type | Notes |
|---|---|---|
| id | integer | Never reused |
| title | string | |
| description | string | May be empty |
| starts_at, ends_at | string | ISO 8601, UTC, ends in Z |
| timezone | string | The venue's zone, as Asia/Kolkata |
| location | string | |
| status | string | published or cancelled |
| capacity | integer | |
| places_left | integer | When read; never below 0 |
| registration_opens_at | string or null | UTC |
| registration_closes_at | string or null | UTC |
| cancellation_deadline | string or null | UTC |
| organizers | list of strings | Current organizers' names |
| cover | string or null | Full address of the cover picture |
| url | string | Full address of the event's page |

Show times in `timezone` for people at the venue.

## Errors

Every error is a problem-details body (RFC 9457), with the
type `application/problem+json`:

```json
{"type": "about:blank", "title": "Not Found",
 "status": 404, "detail": "No published event has this id."}
```

| Status | When |
|---|---|
| 404 | No such event or address |
| 405 | A method the address does not answer; see `Allow` |
| 406 | `Accept` rules out `application/json` |

Read `status` and `type`; `detail` is for people and may
change.

## Caching

Each answer carries a strong `ETag`, a hash of its body,
and `Cache-Control: no-cache`: keep a copy, but ask before
using it. Send the tag back as `If-None-Match`; if nothing
in the answer changed, including places left, the status,
and the organizers, the answer is 304 with no body. There
is no `Last-Modified`: Otahque does not record when an
event last changed.

## Browsers on other sites

Any site's script may read the public addresses
(`Access-Control-Allow-Origin: *`), without cookies, and
may read the `ETag` and send it back in `If-None-Match`.
Organizer addresses send no such
headers, so no other site's page can use them.

## Changes

Within `/api/v1/`, fields and addresses are only added,
never renamed, retyped, or removed; programs must ignore
fields they do not know. A change that would break a
program goes into `/api/v2/`, and `/api/v1/` keeps working
for at least six months after it, with the date announced
on the developers page.

## Writes (planned, Chapters 48 and 49)

The organizer's own events live at `/api/v1/my/events/`.

| Method | Address | Does |
|---|---|---|
| GET | `my/events/` | My events, drafts included |
| POST | `my/events/` | Create a draft |
| GET | `my/events/{id}/` | One of my events |
| PATCH | `my/events/{id}/` | Change its details |
| POST | `my/events/{id}/publish/` | Publish a draft |
| POST | `my/events/{id}/cancel/` | Cancel a published event |
| DELETE | `my/events/{id}/` | Delete a draft |

- An organizer's event carries `ETag: "v{version}"`. A
  PATCH must send it back as `If-Match`: without it, 428
  Precondition Required; with an old one, 412 Precondition
  Failed, and nothing is saved.
- Times must carry an offset (`Z` or `+05:30`); a time
  without one is refused, never guessed.
- `?dry_run=true` on any write checks it and says what it
  would do, and saves nothing.
- Fields that may not be set (`status`, `version`,
  `organizers`) are refused by name, not ignored.
- Every write goes through the same rules and records as
  the site's pages.

Read it as the library’s developer would: it answers every question from Why This Matters, and says what Otahque will not do. Its last section describes writes that do not exist yet. Putting them in now means Chapters 48 and 49 build to a contract the partners have already seen, and a reviewer can object to a rule before it is code. Two rules there matter for programs that act for a person, such as Sam’s AI agent: a time without an offset is refused, never guessed, and every write can be tried first with ?dry_run=true.

Step 3: The packages and the api app

uv add django-cors-headers==4.9.0
uv add --dev openapi-spec-validator==0.9.0
Resolved 33 packages in ...
Installed 1 package in ...
 + django-cors-headers==4.9.0
Resolved 52 packages in ...
Installed 19 packages in ...
 + annotated-types==0.8.0
 + attrs==26.1.0
 + jsonschema==4.26.0
 + jsonschema-path==0.5.0
 + jsonschema-specifications==2025.9.1
 + lazy-object-proxy==1.13.0
 + openapi-schema-validator==0.9.0
 + openapi-spec-validator==0.9.0
 + pathable==0.6.0
 + pydantic==2.14.4
 + pydantic-core==2.50.5
 + pydantic-settings==2.16.3
 + python-dotenv==1.2.4
 + pyyaml==6.0.4
 + referencing==0.37.0
 + rfc3339-validator==0.1.4
 + rpds-py==2026.9.1
 + six==1.17.0
 + typing-inspection==0.4.5

Then a new app for the API, so its views, addresses, and tests stay together:

uv run python manage.py startapp api

The API’s tests go in a folder, as Chapter 34 arranged them for the other apps. Replace the file startapp made with an empty package:

Remove-Item api\tests.py
New-Item -ItemType Directory api\tests | Out-Null
New-Item api\tests\__init__.py | Out-Null
rm api/tests.py
mkdir api/tests
touch api/tests/__init__.py

Give api/apps.py the docstrings the project’s other apps have:

"""Configuration Django reads to load the api app."""
from django.apps import AppConfig


class ApiConfig(AppConfig):
    """Otahque's API for other programs (Chapter 47)."""

    name = 'api'

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

    'django_tasks_db',
    # Chapter 47: the API, and browser access to its
    # public reads from other sites.
    'api.apps.ApiConfig',
]

In pyproject.toml, coverage measures the new app too:

source = ["accounts", "api", "audit", "config", "events",
          "registrations"]

In config/urls.py, remove the second admin.site.site_title = 'Otahque admin' line: it has been there twice since Chapter 23, harmlessly. Check that Django still starts:

uv run python manage.py check
System check identified no issues (0 silenced).

Step 4: The contract as tests

Each promise becomes a test, written before the views. In api/tests/test_contract.py:

"""The API's promises (docs/api/contract.md), Chapter 47.

Each test reads the API as a partner's program would:
signed out, asking for JSON.
"""
from datetime import UTC, timedelta

from django.contrib.auth import get_user_model
from django.test import TestCase
from django.utils import timezone

from config.helpers import in_group, save_event
from events.models import Event
from registrations.models import Registration

User = get_user_model()

FIELDS = {
    'id', 'title', 'description', 'starts_at', 'ends_at',
    'timezone', 'location', 'status', 'capacity',
    'places_left', 'registration_opens_at',
    'registration_closes_at', 'cancellation_deadline',
    'organizers', 'cover', 'url',
}


def soon(days, **changes):
    """Save a published event starting days from now."""
    start = timezone.now().replace(microsecond=0)
    return save_event(starts_at=start + timedelta(days=days),
                      **changes)


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

    @classmethod
    def setUpTestData(cls):
        cls.later = soon(9, title='Later')
        cls.first = soon(2, title='First')
        cls.gone = soon(3, title='Called off',
                        status=Event.Status.CANCELLED)
        cls.draft = soon(1, title='Draft',
                         status=Event.Status.DRAFT)
        cls.over = soon(-3, title='Over')

    def titles(self):
        page = self.client.get('/api/v1/events/')
        self.assertEqual(page.status_code, 200)
        self.assertEqual(page['Content-Type'],
                         'application/json')
        return [e['title'] for e in page.json()['results']]

    def test_signed_out_not_ended_soonest_first(self):
        self.assertEqual(self.titles(),
                         ['First', 'Called off', 'Later'])

    def test_each_event_has_exactly_the_fields(self):
        page = self.client.get('/api/v1/events/')
        for event in page.json()['results']:
            self.assertEqual(set(event), FIELDS)

    def test_queries_do_not_grow_with_events(self):
        for n in range(5):
            soon(4 + n)
        # The events with their places left, then their
        # organizers: two queries, however many events.
        with self.assertNumQueries(2):
            self.titles()


class DetailTests(TestCase):
    """GET /api/v1/events/{id}/."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = in_group('sam@example.org', 'Organizers')
        cls.sai = User.objects.create_user(
            'sai@example.org', display_name='Sai')
        cls.event = soon(5, title='Clinic', capacity=3,
                         timezone='Asia/Kolkata')
        cls.event.add_organizer(cls.sam)
        Registration.objects.create(event=cls.event,
                                    member=cls.sai)

    def read(self, event_id):
        return self.client.get(f'/api/v1/events/{event_id}/')

    def test_fields_and_values(self):
        data = self.read(self.event.pk).json()
        self.assertEqual(set(data), FIELDS)
        self.assertEqual(data['status'], 'published')
        self.assertEqual(data['places_left'], 2)
        self.assertEqual(data['organizers'], ['Sam'])
        self.assertEqual(data['timezone'], 'Asia/Kolkata')
        self.assertIsNone(data['cover'])
        self.assertTrue(data['url'].endswith(
            f'/events/{self.event.pk}/'))

    def test_times_are_utc_ending_in_z(self):
        data = self.read(self.event.pk).json()
        start = self.event.starts_at.astimezone(UTC)
        self.assertEqual(data['starts_at'],
                         start.strftime('%Y-%m-%dT%H:%M:%SZ'))

    def test_no_member_data(self):
        body = self.read(self.event.pk).content.decode()
        for private in ('sai@example.org', 'Sai',
                        'sam@example.org'):
            self.assertNotIn(private, body)

    def test_a_draft_is_like_an_unknown_id(self):
        self.event.status = Event.Status.DRAFT
        self.event.save()
        draft, missing = self.read(self.event.pk), self.read(0)
        self.assertEqual(draft.status_code, 404)
        self.assertEqual(draft.json(), missing.json())

    def test_a_cancelled_event_is_shown_as_cancelled(self):
        self.event.status = Event.Status.CANCELLED
        self.event.save()
        page = self.read(self.event.pk)
        self.assertEqual(page.json()['status'], 'cancelled')

FIELDS is the contract’s field list, written once; Step 7 compares it with the OpenAPI file too. test_queries_do_not_grow_with_events uses assertNumQueries to catch the classic API mistake: a list that runs one more query per event, for its places or its organizers.

The errors, in api/tests/test_errors.py:

"""Errors as problem details, never HTML (Chapter 47)."""
from django.test import TestCase

from config.helpers import save_event

PROBLEM = 'application/problem+json'


class ProblemTests(TestCase):
    """Each error is JSON a program can read."""

    def assertProblem(self, page, status):
        self.assertEqual(page.status_code, status)
        self.assertEqual(page['Content-Type'], PROBLEM)
        body = page.json()
        self.assertEqual(body['status'], status)
        self.assertEqual(body['type'], 'about:blank')
        return body

    def test_an_unknown_id_is_404(self):
        page = self.client.get('/api/v1/events/0/')
        body = self.assertProblem(page, 404)
        self.assertEqual(body['title'], 'Not Found')

    def test_an_unknown_address_is_404_in_json(self):
        for address in ('/api/v1/nope/', '/api/v1/events',
                        '/api/v1/events/abc/'):
            with self.subTest(address):
                page = self.client.get(address)
                self.assertProblem(page, 404)

    def test_post_is_405_with_allow(self):
        page = self.client.post('/api/v1/events/')
        body = self.assertProblem(page, 405)
        self.assertEqual(page['Allow'], 'GET, HEAD')
        self.assertEqual(body['detail'],
                         'POST is not allowed here.')

    def test_only_json_is_406(self):
        page = self.client.get(
            '/api/v1/events/',
            headers={'Accept': 'application/xml'})
        self.assertProblem(page, 406)

    def test_any_type_and_json_are_accepted(self):
        save_event()
        for accept in ('*/*', 'application/json',
                       'text/html, application/json;q=0.5'):
            with self.subTest(accept):
                page = self.client.get(
                    '/api/v1/events/',
                    headers={'Accept': accept})
                self.assertEqual(page.status_code, 200)
uv run python manage.py test api
Found 13 test(s).
Creating test database for alias 'default'...
ERROR: test_a_cancelled_event_is_shown_as_cancelled
ValueError: Content-Type header is "text/html;
    charset=utf-8", not "application/json"
ERROR: test_a_draft_is_like_an_unknown_id
ValueError: Content-Type header is "text/html;
    charset=utf-8", not "application/json"
ERROR: test_each_event_has_exactly_the_fields
ValueError: Content-Type header is "text/html;
    charset=utf-8", not "application/json"
ERROR: test_fields_and_values
ValueError: Content-Type header is "text/html;
    charset=utf-8", not "application/json"
... (12 more like these)
Ran 13 tests in ...s

FAILED (failures=11, errors=5)

All thirteen fail, the same way: there is nothing at /api/v1/ yet, so every request gets the site’s HTML 404 page, which is exactly what the error tests forbid.

Step 5: The representation and the reading views

Errors first, since every view uses them. In api/problems.py:

"""Errors as problem details (RFC 9457), not HTML pages.

A client reads the status code first, then this body: a
title for the kind of problem, a detail for this time.
"""
from django.http import JsonResponse

PROBLEM = 'application/problem+json'

# The status phrases RFC 9110 gives each code: with type
# about:blank, the title is the phrase (RFC 9457 4.2.1).
TITLES = {
    404: 'Not Found',
    405: 'Method Not Allowed',
    406: 'Not Acceptable',
}


def problem(status, detail, **extra):
    """Return a problem-details response for status."""
    body = {'type': 'about:blank', 'title': TITLES[status],
            'status': status, 'detail': detail, **extra}
    return JsonResponse(body, status=status,
                        content_type=PROBLEM)

With type set to about:blank, RFC 9457 asks for the status code’s own phrase as the title, so TITLES holds the three this chapter sends.

The representation, in api/representation.py:

"""An event as the API shows it: the contract's fields.

The fields and their names are listed in
docs/api/contract.md; a test compares them with
docs/api/openapi.yaml. Nothing here names a member.
"""
from datetime import UTC

from django.conf import settings
from django.db.models import Prefetch
from django.utils import timezone

from events.models import Event, OrganizerAssignment


def listed():
    """Events the API shows: published or cancelled.

    Drafts never; places_left and current organizers come
    with the same few queries, however many events.
    """
    current = OrganizerAssignment.objects.filter(
        revoked_at__isnull=True
    ).select_related('member')
    return Event.objects.exclude(
        status=Event.Status.DRAFT
    ).with_places().prefetch_related(Prefetch(
        'organizer_assignments', queryset=current,
        to_attr='current_organizers'))


def upcoming():
    """Return listed events not yet ended, soonest first."""
    now = timezone.now()
    return listed().filter(ends_at__gt=now).order_by(
        'starts_at', 'id')


def absolute(path):
    """Return the full address of a path on Otahque."""
    return settings.SITE_URL + path


def in_utc(moment):
    """Return moment in UTC; an empty time stays None."""
    return moment.astimezone(UTC) if moment else None


def event_data(event):
    """Return the contract's fields for one event.

    Times stay aware datetimes: JsonResponse writes them in
    ISO 8601, and UTC ones end in Z.
    """
    return {
        'id': event.pk,
        'title': event.title,
        'description': event.description,
        'starts_at': in_utc(event.starts_at),
        'ends_at': in_utc(event.ends_at),
        'timezone': event.timezone,
        'location': event.location,
        'status': event.status,
        'capacity': event.capacity,
        'places_left': max(event.places_left, 0),
        'registration_opens_at': in_utc(
            event.registration_opens_at),
        'registration_closes_at': in_utc(
            event.registration_closes_at),
        'cancellation_deadline': in_utc(
            event.cancellation_deadline),
        'organizers': [assignment.member.display_name
                       for assignment
                       in event.current_organizers],
        'cover': (absolute(event.cover.url)
                  if event.cover else None),
        'url': absolute(event.get_absolute_url()),
    }

listed() is the one place that says which events the API may show: published and cancelled, never drafts. with_places() is Chapter 31’s annotation, so places left come in the same query. Prefetch(..., to_attr='current_organizers') fetches every listed event’s current organizers in one more query and leaves them on each event as a list. event_data() builds the dictionary the contract describes, field by field: nothing reaches the client because the model happens to have it.

The views, in api/views.py:

"""The API's first endpoints, written by hand (Chapter 47).

Each view is public, like the event page: anyone may read
published and cancelled events. Each answers only GET and
HEAD, only in JSON, and says what went wrong in a problem
body. Chapter 48 rebuilds the same answers with Django
REST framework.
"""
from functools import wraps

from django.contrib.auth.decorators import login_not_required
from django.http import JsonResponse

from .problems import problem
from .representation import event_data, listed, upcoming

JSON = 'application/json'


def read_only(view):
    """Let view answer GET and HEAD, in JSON; refuse others.

    Public, like the event page.
    """
    @login_not_required
    @wraps(view)
    def checked(request, *args, **kwargs):
        if request.method not in ('GET', 'HEAD'):
            response = problem(
                405, f'{request.method} is not allowed here.')
            response['Allow'] = 'GET, HEAD'
            return response
        if not request.accepts(JSON):
            return problem(406, 'This address answers only '
                           'in application/json.')
        return view(request, *args, **kwargs)
    return checked


@read_only
def event_list(request):
    """Send published and cancelled events not yet ended."""
    events = [event_data(event) for event in upcoming()]
    return JsonResponse({'results': events})


@read_only
def event_detail(request, event_id):
    """Send one published or cancelled event, or 404."""
    event = listed().filter(pk=event_id).first()
    if event is None:
        return problem(404, 'No published event has this '
                       'id.')
    return JsonResponse(event_data(event))


@login_not_required
def not_found(request, rest):
    """Answer any other address under /api/v1/ with 404."""
    return problem(404, 'No such address. Addresses end '
                   'with a slash, as /api/v1/events/ does.')

read_only wraps each view with the contract’s rules for reading: public, like the event page (Chapter 39’s middleware would otherwise send programs to the sign-in page); only GET and HEAD, with 405 and an Allow header for the rest; and 406 unless the client accepts JSON. request.accepts() treats a request with no Accept header as accepting anything, as HTTP says. not_found takes every other address under /api/v1/, so a program never gets the site’s HTML page.

The addresses, in api/urls.py:

"""Addresses of the API, under /api/v1/ (Chapter 47)."""
from django.urls import path

from . import views

app_name = 'api'

urlpatterns = [
    path('events/', views.event_list, name='event_list'),
    path('events/<int:event_id>/', views.event_detail,
         name='event_detail'),
    # 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'),
]

and in config/urls.py, below the registrations line:

    path('api/v1/', include('api.urls')),
uv run python manage.py test api
Found 13 test(s).
Creating test database for alias 'default'...
...
Ran 13 tests in ...s

OK

Common Error: a draft answering 200

What you see: GET /api/v1/events/12/ returns an event whose status is draft.

Why it happens: the detail view used Event.objects.get(pk=...) instead of listed(), the one queryset that leaves drafts out.

How to fix it: every API view starts from listed() or upcoming(). test_a_draft_is_like_an_unknown_id also checks that a draft’s 404 is identical to a missing id’s, so the answer does not even reveal that the draft exists.

Step 6: ETags and 304 Not Modified

The tests, in api/tests/test_caching.py:

"""ETags that change whenever the answer does (Chapter 47).

The event's version counts edits only: publishing,
cancelling, and every place taken leave it alone. So the
tag is a hash of the body, which changes with all of them.
"""
from datetime import timedelta

from django.contrib.auth import get_user_model
from django.test import TestCase
from django.utils import timezone

from config.helpers import save_event
from registrations.models import Registration

User = get_user_model()


class ETagTests(TestCase):
    """GET with If-None-Match."""

    def setUp(self):
        start = timezone.now() + timedelta(days=5)
        self.event = save_event(starts_at=start)
        self.address = f'/api/v1/events/{self.event.pk}/'

    def tag(self):
        return self.client.get(self.address)['ETag']

    def test_a_quoted_tag_and_no_cache(self):
        page = self.client.get(self.address)
        self.assertRegex(page['ETag'], r'^"[0-9a-f]{32}"$')
        self.assertEqual(page['Cache-Control'], 'no-cache')

    def test_unchanged_is_304_with_no_body(self):
        page = self.client.get(
            self.address, headers={'If-None-Match': self.tag()})
        self.assertEqual(page.status_code, 304)
        self.assertEqual(page.content, b'')

    def test_cancelling_changes_the_tag_not_the_version(self):
        before, version = self.tag(), self.event.version
        self.event.cancel()
        self.event.refresh_from_db()
        self.assertEqual(self.event.version, version)
        self.assertNotEqual(self.tag(), before)

    def test_a_place_taken_changes_the_tag(self):
        before = self.tag()
        sai = User.objects.create_user('sai@example.org',
                                       display_name='Sai')
        Registration.objects.create(event=self.event,
                                    member=sai)
        page = self.client.get(
            self.address, headers={'If-None-Match': before})
        self.assertEqual(page.status_code, 200)
        self.assertEqual(page.json()['places_left'], 39)

test_cancelling_changes_the_tag_not_the_version is Table 47.3 as a test: it checks that version stays the same and that the tag changes anyway.

uv run python manage.py test api.tests.test_caching
Found 4 test(s).
Creating test database for alias 'default'...
ERROR: test_a_place_taken_changes_the_tag
KeyError: 'etag'
ERROR: test_a_quoted_tag_and_no_cache
KeyError: 'etag'
ERROR: test_cancelling_changes_the_tag_not_the_version
KeyError: 'etag'
ERROR: test_unchanged_is_304_with_no_body
KeyError: 'etag'
Ran 4 tests in ...s

FAILED (errors=4)

In api/views.py, the imports become:

from functools import wraps

from django.contrib.auth.decorators import login_not_required
from django.http import JsonResponse
from django.middleware.http import ConditionalGetMiddleware
from django.utils.cache import patch_cache_control
from django.utils.decorators import decorator_from_middleware

from .problems import problem
from .representation import event_data, listed, upcoming

directly below JSON = 'application/json':

# Adds an ETag made from the body, and answers a matching
# If-None-Match with 304 Not Modified and no body.
conditional = decorator_from_middleware(
    ConditionalGetMiddleware)

read_only now also sets Cache-Control: no-cache, which, despite its name, means “keep a copy, but ask before using it”:

def read_only(view):
    """Let view answer GET and HEAD, in JSON; refuse others.

    Public, like the event page; a client must revalidate
    a stored copy before using it (no-cache).
    """
    @login_not_required
    @wraps(view)
    def checked(request, *args, **kwargs):
        if request.method not in ('GET', 'HEAD'):
            response = problem(
                405, f'{request.method} is not allowed here.')
            response['Allow'] = 'GET, HEAD'
            return response
        if not request.accepts(JSON):
            return problem(406, 'This address answers only '
                           'in application/json.')
        response = view(request, *args, **kwargs)
        patch_cache_control(response, no_cache=True)
        return response
    return checked

and the two reading views gain @conditional under @read_only:

@read_only
@conditional
def event_list(request):
    """Send published and cancelled events not yet ended."""
    events = [event_data(event) for event in upcoming()]
    return JsonResponse({'results': events})


@read_only
@conditional
def event_detail(request, event_id):
    """Send one published or cancelled event, or 404."""
    event = listed().filter(pk=event_id).first()
    if event is None:
        return problem(404, 'No published event has this '
                       'id.')
    return JsonResponse(event_data(event))

The order matters. read_only is outermost, so a POST is refused before anything is built. conditional sits next to the view, so it sees the finished JSON, hashes it into the ETag, and turns the answer into a 304 when the client’s If-None-Match matches. Django writes the tag in quotes, as HTTP requires.

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

OK

Common Error: an ETag from a field

What you see: a partner’s site keeps showing an event as published after it was cancelled.

Why it happens: the ETag came from a field, such as version, that does not change with everything the answer shows. The server compared tags, found them equal, and answered 304.

How to fix it: take the tag from the answer itself, as conditional does, or from a field you have proved changes with every field shown. Table 47.3 is that proof done the other way round.

Step 7: The contract for machines

Write docs/api/openapi.yaml. It begins with the API’s description and its two paths:

openapi: 3.1.0
info:
  title: Otahque API
  version: 1.0.0
  summary: Published community events, for other programs.
  description: >-
    Read Otahque's published and cancelled events. Times
    are UTC; show them in each event's timezone. The rules
    are in docs/api/contract.md.
servers:
  - url: /api/v1
paths:
  /events/:
    get:
      operationId: listEvents
      summary: List events that have not ended yet.
      description: >-
        Published and cancelled events whose end is still
        to come, soonest start first. Drafts never appear.
      responses:
        '200':
          description: The events.
          headers:
            ETag:
              $ref: '#/components/headers/ETag'
          content:
            application/json:
              schema:
                type: object
                required: [results]
                properties:
                  results:
                    type: array
                    items:
                      $ref: '#/components/schemas/Event'
        '304':
          $ref: '#/components/responses/NotModified'
        '405':
          $ref: '#/components/responses/Problem'
        '406':
          $ref: '#/components/responses/Problem'
  /events/{id}/:
    get:
      operationId: getEvent
      summary: Read one published or cancelled event.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: The event.
          headers:
            ETag:
              $ref: '#/components/headers/ETag'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Event'
        '304':
          $ref: '#/components/responses/NotModified'
        '404':
          $ref: '#/components/responses/Problem'
        '405':
          $ref: '#/components/responses/Problem'
        '406':
          $ref: '#/components/responses/Problem'

and ends with the pieces the paths refer to, under components:

components:
  headers:
    ETag:
      description: >-
        A hash of the body. Send it as If-None-Match to get
        304 while nothing has changed.
      schema:
        type: string
  responses:
    NotModified:
      description: Nothing changed since the ETag you sent.
    Problem:
      description: What went wrong (RFC 9457).
      content:
        application/problem+json:
          schema:
            $ref: '#/components/schemas/Problem'
  schemas:
    Event:
      type: object
      required: [id, title, description, starts_at, ends_at,
                 timezone, location, status, capacity,
                 places_left, registration_opens_at,
                 registration_closes_at,
                 cancellation_deadline, organizers, cover,
                 url]
      properties:
        id:
          type: integer
        title:
          type: string
        description:
          type: string
        starts_at:
          type: string
          format: date-time
          description: UTC, ending in Z.
        ends_at:
          type: string
          format: date-time
        timezone:
          type: string
          description: The venue's zone, such as Asia/Kolkata.
        location:
          type: string
        status:
          type: string
          enum: [published, cancelled]
        capacity:
          type: integer
        places_left:
          type: integer
          minimum: 0
          description: A snapshot, when the event was read.
        registration_opens_at:
          type: [string, 'null']
          format: date-time
        registration_closes_at:
          type: [string, 'null']
          format: date-time
        cancellation_deadline:
          type: [string, 'null']
          format: date-time
        organizers:
          type: array
          items:
            type: string
          description: Current organizers' display names.
        cover:
          type: [string, 'null']
          format: uri
        url:
          type: string
          format: uri
          description: The event's page on Otahque.
    Problem:
      type: object
      required: [type, title, status]
      properties:
        type:
          type: string
        title:
          type: string
        status:
          type: integer
        detail:
          type: string

$ref points at a definition elsewhere in the file, so the Event schema and the Problem answer are written once. type: [string, 'null'] is OpenAPI 3.1’s way, borrowed from JSON Schema, of saying “a string, or null”. Every operation has a summary and an operationId: that is what an AI agent, or any tool, shows as the name and purpose of the action.

The tests, in api/tests/test_openapi.py:

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

docs/api/openapi.yaml is written by hand in Chapter 47, so
these tests keep it honest: it must be valid OpenAPI 3.1,
and its Event must have exactly the fields the API sends.
"""
from django.conf import settings
from django.test import TestCase
from openapi_spec_validator import validate
from openapi_spec_validator.readers import read_from_filename

from api.tests.test_contract import FIELDS

SPEC = settings.BASE_DIR / 'docs/api/openapi.yaml'


class OpenAPITests(TestCase):
    """The machine-readable contract."""

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.spec, _ = read_from_filename(str(SPEC))

    def test_it_is_valid_openapi_3_1(self):
        self.assertEqual(self.spec['openapi'], '3.1.0')
        validate(self.spec)

    def test_event_fields_match_the_api(self):
        event = self.spec['components']['schemas']['Event']
        self.assertEqual(set(event['properties']), FIELDS)
        self.assertEqual(set(event['required']), FIELDS)

    def test_it_is_served_to_programs(self):
        page = self.client.get('/api/v1/openapi.yaml')
        self.assertEqual(page.status_code, 200)
        self.assertEqual(page['Content-Type'],
                         'application/yaml')
        self.assertIn(b'openapi: 3.1.0',
                      b''.join(page.streaming_content))
uv run python manage.py test api.tests.test_openapi
Found 3 test(s).
Creating test database for alias 'default'...
FAIL: test_it_is_served_to_programs
AssertionError: 404 != 200
Ran 3 tests in ...s

FAILED (failures=1)

The file is valid and its fields match; only the address that serves it is missing. In api/views.py, the imports become:

from functools import wraps

from django.conf import settings
from django.contrib.auth.decorators import login_not_required
from django.http import FileResponse, JsonResponse
from django.middleware.http import ConditionalGetMiddleware
from django.utils.cache import patch_cache_control
from django.utils.decorators import decorator_from_middleware

from .problems import problem
from .representation import event_data, listed, upcoming

above not_found:

@read_only
def openapi(request):
    """Send the contract for programs, openapi.yaml."""
    path = settings.BASE_DIR / 'docs/api/openapi.yaml'
    return FileResponse(open(path, 'rb'),
                        content_type='application/yaml')

and in api/urls.py, above the comment that starts # Last:

    path('openapi.yaml', views.openapi, name='openapi'),

The order of the patterns matters here: the catch-all must stay last, or it would answer for openapi.yaml too.

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

OK

Step 8: Browsers on other sites

The tests, in api/tests/test_cors.py:

"""Browser access from other sites (Chapter 47, N47.8).

A page on another site may read the public addresses,
without cookies; nowhere else sends CORS headers.
"""
from django.test import TestCase

from config.helpers import save_event

LIBRARY = {'Origin': 'https://library.example'}


class CorsTests(TestCase):
    """django-cors-headers, limited by CORS_URLS_REGEX."""

    def test_any_site_may_read_the_events(self):
        save_event()
        page = self.client.get('/api/v1/events/',
                               headers=LIBRARY)
        self.assertEqual(page['Access-Control-Allow-Origin'],
                         '*')
        self.assertEqual(
            page['Access-Control-Expose-Headers'], 'ETag')
        self.assertNotIn('Access-Control-Allow-Credentials',
                         page)

    def test_a_preflight_offers_reading_only(self):
        page = self.client.options(
            '/api/v1/events/',
            headers={**LIBRARY,
                     'Access-Control-Request-Method': 'PATCH'})
        self.assertEqual(page['Access-Control-Allow-Methods'],
                         'GET, HEAD, OPTIONS')

    def test_a_script_may_send_if_none_match(self):
        page = self.client.options(
            '/api/v1/events/',
            headers={**LIBRARY,
                     'Access-Control-Request-Method': 'GET',
                     'Access-Control-Request-Headers':
                         'if-none-match'})
        self.assertEqual(page['Access-Control-Allow-Headers'],
                         'accept, if-none-match')

    def test_the_site_and_other_addresses_send_none(self):
        for address in ('/events/', '/api/v1/nope/'):
            with self.subTest(address):
                page = self.client.get(address,
                                       headers=LIBRARY)
                self.assertNotIn(
                    'Access-Control-Allow-Origin', page)
uv run python manage.py test api.tests.test_cors
Found 4 test(s).
Creating test database for alias 'default'...
ERROR: test_a_preflight_offers_reading_only
KeyError: 'access-control-allow-methods'
ERROR: test_a_script_may_send_if_none_match
KeyError: 'access-control-allow-headers'
ERROR: test_any_site_may_read_the_events
KeyError: 'access-control-allow-origin'
Ran 4 tests in ...s

FAILED (errors=3)

In config/settings.py, INSTALLED_APPS ends:

    'django_tasks_db',
    # Chapter 47: the API, and browser access to its
    # public reads from other sites.
    'api.apps.ApiConfig',
    'corsheaders',
]

the middleware goes second in MIDDLEWARE, below the request id:

    # Chapter 47: as high as possible, before any middleware
    # that can answer by itself (django-cors-headers' advice).
    'corsheaders.middleware.CorsMiddleware',

and at the end of the file:

# Browser access from other sites (Chapter 47, N47.8). Only
# the public reads and the contract file: any site may read
# them, without cookies. Every other address, the organizer
# endpoints included, sends no CORS headers, so a browser
# on another site cannot read its answers.
CORS_URLS_REGEX = r'^/api/v1/(events/.*|openapi\.yaml)$'
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_METHODS = ['GET', 'HEAD', 'OPTIONS']
CORS_ALLOW_CREDENTIALS = False
# A script may read the ETag and send it back: If-None-Match
# is not a header browsers send freely, so the preflight
# must allow it.
CORS_EXPOSE_HEADERS = ['ETag']
CORS_ALLOW_HEADERS = ['accept', 'if-none-match']

CORS_URLS_REGEX is the setting that keeps everything else private: the middleware does nothing for an address that does not match it. CORS_ALLOW_ALL_ORIGINS with no credentials means any site’s script may read these answers, but its requests carry no cookies, so they read exactly what a signed-out visitor sees.

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

OK

Common Error: the second fetch fails

What you see: a partner’s page reads the list once, then fails with “TypeError: Failed to fetch” when it sends the ETag back.

Why it happens: If-None-Match is not one of the few headers browsers send to another origin freely, so the browser first asks in a preflight, and django-cors-headers’ default list of allowed headers does not include it. The unit tests passed; only a real browser showed it, in this chapter’s own checks.

How to fix it: name it in CORS_ALLOW_HEADERS, as above, and keep test_a_script_may_send_if_none_match to hold it.

Step 9: A page for developers

Partners need to find the API. The test, at the end of api/tests/test_openapi.py:

class DevelopersPageTests(TestCase):
    """/developers/, linked from every page's footer."""

    def test_open_signed_out_and_linked(self):
        page = self.client.get('/developers/')
        self.assertContains(page, '<h1>For developers</h1>')
        self.assertContains(page, '/api/v1/openapi.yaml')
        home = self.client.get('/')
        self.assertContains(home, 'href="/developers/"')
uv run python manage.py test api.tests.test_openapi
Found 4 test(s).
Creating test database for alias 'default'...
FAIL: test_open_signed_out_and_linked
AssertionError: 404 != 200 : Couldn't retrieve content:
    Response code was 404 (expected 200)
Ran 4 tests in ...s

FAILED (failures=1)

The page, in api/templates/api/developers.html:

{% extends "base.html" %}

{% block title %}For developers | Otahque{% endblock %}

{% block content %}
  <h1>For developers</h1>
  <p>Show Otahque's events on your own
    site, or in a calendar, from a program. Anyone may read
    published events; no account is needed.</p>

  <div class="dev-cards">
    <section class="dev-card" aria-labelledby="dev-read">
      <h2 id="dev-read">Read events</h2>
      <dl class="dev-endpoints">
        <dt><code>GET /api/v1/events/</code></dt>
        <dd>Published and cancelled events not yet ended,
          soonest first.</dd>
        <dt><code>GET /api/v1/events/{id}/</code></dt>
        <dd>One event. A draft, or an id that does not
          exist, is 404.</dd>
      </dl>
      <pre class="dev-example"><code>{{ example }}</code></pre>
    </section>

    <section class="dev-card" aria-labelledby="dev-rules">
      <h2 id="dev-rules">The rules we keep</h2>
      <ul>
        <li>Times are in UTC, ending in <code>Z</code>,
          with the event's time zone by name.</li>
        <li>Errors come as problem details,
          <code>application/problem+json</code>.</li>
        <li>Send <code>If-None-Match</code> with the
          <code>ETag</code> you were given: an unchanged
          event costs a 304 and no body.</li>
        <li>Within <code>/api/v1/</code>, fields are only
          ever added; a change that would break a program
          gets <code>/api/v2/</code>.</li>
      </ul>
    </section>

    <section class="dev-card" aria-labelledby="dev-contract">
      <h2 id="dev-contract">The contract</h2>
      <p>Every field, error, and header is described in
        OpenAPI 3.1, which tools and AI agents can read.</p>
      <p><a class="btn btn-primary btn-sm"
            href="{% url 'api:openapi' %}">Download
          openapi.yaml</a></p>
    </section>
  </div>
{% endblock %}

In api/views.py, the imports become:

from functools import wraps

from django.conf import settings
from django.contrib.auth.decorators import login_not_required
from django.http import FileResponse, JsonResponse
from django.middleware.http import ConditionalGetMiddleware
from django.shortcuts import render
from django.urls import reverse
from django.utils.cache import patch_cache_control
from django.utils.decorators import decorator_from_middleware
from django.views.decorators.http import require_safe

from .problems import problem
from .representation import (absolute, event_data, listed,
                             upcoming)

and at the end:

@login_not_required
@require_safe
def developers(request):
    """Show the page for people who write programs."""
    events = absolute(reverse('api:event_list'))
    return render(request, 'api/developers.html', {
        'example': f'curl {events}',
    })

The curl example is built in the view from SITE_URL, so it always names this site’s own address. In config/urls.py, above from . import views:

from api import views as api_views

and below the API’s line:

    path('developers/', api_views.developers,
         name='developers'),

In templates/includes/site_footer.html, below the help line:

  <p><a href="{% url 'developers' %}">For developers</a></p>

The cards get their own styles. Tailwind only reads the folders it is told about, so in static/otahque/source.css, below the accounts @source line:

@source "../../api/templates";

and above .form-actions:

  /* Chapter 47: the page for developers, in cards that sit
     side by side when there is room. */
  .dev-cards {
    display: grid;
    grid-template-columns:
      repeat(auto-fit, minmax(18rem, 1fr));
    gap: 1rem;
  }
  .dev-card {
    display: grid;
    align-content: start;
    gap: 0.75rem;
    padding: 1.25rem;
    border: 1px solid var(--color-base-300);
    border-top: 6px solid var(--color-primary);
    border-radius: var(--radius-box);
    background-color: var(--color-base-100);
  }
  .dev-card h2 {
    font-size: 1.25rem;
    font-weight: 700;
  }
  .dev-card ul {
    display: grid;
    gap: 0.5rem;
    padding-left: 1.25rem;
    list-style: disc;
  }
  .dev-endpoints dt {
    margin-top: 0.5rem;
    font-weight: 600;
    overflow-wrap: anywhere;
  }
  .dev-example {
    padding: 0.75rem;
    border-radius: var(--radius-field);
    background-color: var(--color-neutral);
    color: var(--color-neutral-content);
    font-size: 0.875rem;
    white-space: pre-wrap;
    overflow-wrap: anywhere;
  }

Build the stylesheet, then run Chapter 39’s guard on public pages:

npm run build
uv run python manage.py test config.tests.test_public
Found 3 test(s).
Creating test database for alias 'default'...
FAIL: test_a_visitor_is_sent_to_sign_in_elsewhere
    [developers]
AssertionError: 200 != 302 : Response didn't redirect as
    expected: Response code was 200 (expected 302)
FAIL: test_exactly_these_pages_are_public
AssertionError: Items in the first set but not the second:
Ran 3 tests in ...s

FAILED (failures=2)

This failure is the guard doing its job: five new addresses are open to visitors, and the test insists that every public page is listed on purpose. In config/tests/test_public.py, the docstring’s first paragraph gains a line:

Chapter 42 adds the media view, which decides per file.
Chapter 47 adds the API's public reads and the page for
developers.

PUBLIC becomes:

PUBLIC = {'events:home', 'events:list', 'events:detail',
          'media', 'developers', 'api:event_list',
          'api:event_detail', 'api:openapi', 'api:not_found'}

and own_pages() reads the API’s addresses too:

    for app in ('accounts', 'events', 'registrations', 'api'):
uv run python manage.py test api config.tests.test_public
Found 28 test(s).
Creating test database for alias 'default'...
...
Ran 28 tests in ...s

OK

Step 10: Read it as a client

Start the server in one terminal:

uv run python manage.py runserver

and, in another, ask as a program would. In PowerShell, call curl.exe: plain curl there is a different command.

An event that does not exist:

curl.exe -s -i http://127.0.0.1:8000/api/v1/events/0/
curl -s -i http://127.0.0.1:8000/api/v1/events/0/
HTTP/1.1 404 Not Found
Date: ...
Server: WSGIServer/0.2 CPython/3.14.9
Content-Type: application/problem+json
ETag: "..."
Cache-Control: no-cache
X-Frame-Options: DENY
Content-Length: 105
Vary: Cookie, origin
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
X-Request-ID: ...

{"type": "about:blank", "title": "Not Found", "status": 404,
    "detail": "No published event has this id."}

A client that will not take JSON:

curl.exe -s -H "Accept: application/xml" `
  http://127.0.0.1:8000/api/v1/events/
curl -s -H "Accept: application/xml" \
  http://127.0.0.1:8000/api/v1/events/
{"type": "about:blank", "title": "Not Acceptable", "status":
    406, "detail": "This address answers only in
    application/json."}

And the list’s headers only, the body thrown away:

curl.exe -s -D - -o NUL http://127.0.0.1:8000/api/v1/events/
curl -s -D - -o /dev/null http://127.0.0.1:8000/api/v1/events/
HTTP/1.1 200 OK
Date: ...
Server: WSGIServer/0.2 CPython/3.14.9
Content-Type: application/json
ETag: "..."
Cache-Control: no-cache
X-Frame-Options: DENY
Content-Length: 1947
Vary: Cookie, origin
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
X-Request-ID: ...

Then open the site in a browser and follow For developers in the footer. Figure 47.3 shows the page at desktop and phone widths.

Two screenshots of the For developers page. Left, at 1280 pixels: the heading, a sentence saying anyone may read published events with no account, and three cards side by side, each with a blue top edge: Read events, listing GET /api/v1/events/ and GET /api/v1/events/{id}/ with a dark box holding a curl command; The rules we keep, four bullets on UTC times, problem details, If-None-Match, and additions only within version 1; and The contract, with a Download openapi.yaml button. Right, at 390 pixels: the same cards stacked, the curl command wrapping inside its box.
Figure 47.3 — The page for developers, on a desktop and a phone.

Step 11: The checks, and the commit

Stop the server with Ctrl+C, then:

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 645 test(s).
System check identified no issues (0 silenced).
Ran 645 tests in ...s
OK
== all checks passed
git add .
git status --short
git commit -m "Publish events through an API"
A  api/__init__.py
A  api/admin.py
A  api/apps.py
A  api/migrations/__init__.py
A  api/models.py
A  api/problems.py
A  api/representation.py
A  api/templates/api/developers.html
A  api/tests/__init__.py
A  api/tests/test_caching.py
A  api/tests/test_contract.py
A  api/tests/test_cors.py
A  api/tests/test_errors.py
A  api/tests/test_openapi.py
A  api/urls.py
A  api/views.py
M  config/settings.py
M  config/tests/test_public.py
M  config/urls.py
A  docs/api/contract.md
A  docs/api/openapi.yaml
M  pyproject.toml
M  static/otahque/site.css
M  static/otahque/source.css
M  templates/includes/site_footer.html
M  uv.lock
[main 1a2b3c4] Publish events through an API
 26 files changed, 1448 insertions(+), 4 deletions(-)
 create mode 100644 api/__init__.py
 create mode 100644 api/admin.py
 create mode 100644 api/apps.py
 create mode 100644 api/migrations/__init__.py
 create mode 100644 api/models.py
 create mode 100644 api/problems.py
 create mode 100644 api/representation.py
 create mode 100644 api/templates/api/developers.html
 create mode 100644 api/tests/__init__.py
 create mode 100644 api/tests/test_caching.py
 create mode 100644 api/tests/test_contract.py
 create mode 100644 api/tests/test_cors.py
 create mode 100644 api/tests/test_errors.py
 create mode 100644 api/tests/test_openapi.py
 create mode 100644 api/urls.py
 create mode 100644 api/views.py
 create mode 100644 docs/api/contract.md
 create mode 100644 docs/api/openapi.yaml

If something goes wrong

Table 47.5 — Recovery for Chapter 47
What you see Likely cause What to do
302 to /accounts/login/ from /api/v1/ A view without read_only or login_not_required Wrap it; Chapter 39's middleware covers every view
An HTML 404 page from /api/v1/ The catch-all pattern is missing, or not last Keep path('<path:rest>', ...) as the last pattern
The list misses an event It is a draft, or it has ended Read it by id; the list holds events not yet ended
assertNumQueries fails with a growing count Organizers read one event at a time Use listed(), which prefetches them
No ETag, never 304 @conditional missing, or above @read_only Put it next to the view, under @read_only
The browser test fails: CORS The address is outside CORS_URLS_REGEX, or the header not allowed Check the regex; add the header to CORS_ALLOW_HEADERS
ModuleNotFoundError: openapi_spec_validator The development packages are not installed uv sync installs them
The stylesheet lacks the cards Tailwind does not read api/templates Add the @source line, then npm run build
PAGE 003

Verify Your Work

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

Table 47.6 — Verification checklist for Chapter 47
Check Command or action Expected result
Starting point test --parallel Found 620 test(s); OK
Packages and app uv add twice; startapp api; check Both added; no issues
The contract as tests test api Red first: 13 failures; then 13 tests OK
ETags test api.tests.test_caching Red first; then 4 tests OK
The OpenAPI file test api.tests.test_openapi One failure, then 3 tests OK
Other sites test api.tests.test_cors Red first; then 4 tests OK
The developers page test api config.tests.test_public Chapter 39's guard red on purpose; then 28 tests OK
As a client curl.exe or curl, three requests 404 and 406 as problem details; the list with an ETag and no-cache
In a browser For developers, at 390 and 1280 px Three cards; no sideways scroll
All checks uv run python check.py == all checks passed; Ran 645 tests
Commit git log --oneline -1 Publish events through an API
Not verified macOS and Linux shells; a partner's real site Run Step 10 in your own shell

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 46 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 followed the footer link to the developers page, then, from a page on another origin (localhost instead of 127.0.0.1, which a browser treats as a different site), read the event list with fetch(), read its ETag, and sent it back in If-None-Match, getting 304. That check found the missing If-None-Match in the allowed headers, which the unit tests had not. One sample event was added for it and deleted afterwards.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 1 Why write the contract before the code?

Flip to check your answerFold answer back

Answer. So the promises are decided on purpose, by the people who will keep them, and can be reviewed and tested; code written first makes whatever it happens to do into the contract.

Que. 2 A client sends GET /api/v1/events/12/, and event 12 is a draft. What does it get, and why exactly that?

Flip to check your answerFold answer back

Answer. 404, with the same problem body as an id that does not exist. A draft is not part of the public API, and a different answer would tell outsiders that the draft exists.

Que. 3 Why can’t the event’s version be the ETag of the public answer?

Flip to check your answerFold answer back

Answer. version counts edits, but the answer also changes when the event is published or cancelled, when places are taken, and when organizers change. A partner would get 304 for a changed event. The tag must change whenever the answer does, so it is a hash of the answer.

Que. 4 What does CORS_URLS_REGEX protect?

Flip to check your answerFold answer back

Answer. Every address it does not match: they send no CORS headers, so no page on another site can read their answers. Only the public reads and the contract file are shared.

Que. 5 The library’s program receives a field it has never seen, "room": "B2". What should it do, and what does the contract promise?

Flip to check your answerFold answer back

Answer. Ignore it. Within /api/v1/, fields are only added, so ignoring unknown fields is what lets Otahque add them without breaking anyone.

Mini-Challenge

The contract says the list holds events not yet ended, but an event’s own address still answers after it ends, because a link someone saved should keep working. Write a test, in api/tests/test_ended.py, that saves an event that ended three days ago and checks both.

Hint: save_event() takes starts_at; give it a time in the past.

Model answer:

"""Mini-Challenge: an ended event, by list and by id."""
from datetime import timedelta

from django.test import TestCase
from django.utils import timezone

from config.helpers import save_event


class EndedTests(TestCase):
    """The list is upcoming; an id still finds the past."""

    def test_not_listed_but_readable_by_id(self):
        start = timezone.now() - timedelta(days=3)
        event = save_event(starts_at=start)
        listed = self.client.get('/api/v1/events/').json()
        self.assertEqual(listed['results'], [])
        page = self.client.get(f'/api/v1/events/{event.pk}/')
        self.assertEqual(page.status_code, 200)
        self.assertEqual(page.json()['id'], event.pk)
uv run python manage.py test api.tests.test_ended
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

  • An API is a contract: write who it serves, its addresses, fields, errors, caching, and compatibility promise before the code, then turn each promise into a test.
  • A representation is chosen, not copied from the model: times in UTC with the zone’s name, computed fields, and nothing private.
  • HTTP already defines methods and status codes; use them as defined, including 405 with Allow and 406.
  • Errors are problem details, one shape for every error a program can meet.
  • An ETag must change whenever the answer changes; a hash of the answer always does.
  • CORS shares answers with other sites’ pages; limit it to what is public, and check it in a real browser.
  • A machine-readable contract can be tested against the API, and read by tools and AI agents.

Key terms

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

Table 47.7 — Key terms from Chapter 47
Term Meaning
API Addresses that answer programs in a format they read, with promises.
Contract The written promises: addresses, fields, errors, and change rules.
Resource What an address names: an event, a list of events.
Representation The document sent for a resource; here, JSON.
Safe method Changes nothing on the server: GET, HEAD.
Idempotent method Has the same effect sent once or many times.
Content negotiation Choosing the format from the client's Accept header.
Problem details RFC 9457's JSON shape for errors.
ETag A tag that changes whenever the representation does.
Conditional request A request that depends on a tag: If-None-Match, If-Match.
Origin Scheme, host, and port of a page.
CORS Headers that let pages from other origins read an answer.
OpenAPI A standard, machine-readable description of an HTTP API.

Readiness checkpoint: you are ready for Chapter 48 when uv run python check.py ends with “all checks passed” and 645 tests, curl shows problem details for a missing event, your browser shows the developers page from the footer, and git log --oneline -1 shows this chapter’s commit.

Git Commit

Your Chapter 47 work was committed once, in Step 11, as “Publish events through an API”: the contract and its OpenAPI copy, the api app with its views, addresses, template, and tests, the settings, the project’s addresses, the footer, the stylesheet and its compiled CSS, pyproject.toml and uv.lock, and the route test. If you kept the Mini-Challenge, commit it on its own:

git add api/tests/test_ended.py
git commit -m "Read an ended event by its id"
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 caching incident and to how an API changes over years. 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): What is an API contract, and what goes in one?

What the interviewer is testing: Do you see an API as promises, not code?

Flip to check your answerFold answer back

Perfect answer: An API contract is the written set of promises an API makes to the programs that use it. For each address: the methods it answers, the fields of each answer with their types and meaning, the errors and how they look, what a client may cache, and how the API will change. Both sides build against it: clients rely on it, and the server turns each promise into a test. Otahque’s says who it serves, lists two reading addresses, fixes times to UTC with the zone’s name, keeps drafts and member data out, sends errors as problem details, and promises that version 1 only ever grows.

Table 47.8 — What Otahque’s contract fixes
Part Otahque's choice
Who Partners and calendars read; organizers' programs write later
Addresses /api/v1/events/ and /api/v1/events/{id}/
Fields The 16 of Figure 47.1; nothing private
Errors Problem details, application/problem+json
Caching A strong ETag from the body; no-cache
Change Only additions within v1; breaking changes in v2

Behind the scenes:

docs/api/contract.md   people read it
docs/api/openapi.yaml  tools and agents read it
api/tests/             the server proves it

Code proof: the contract’s tests:

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

OK

Common mistakes:

  • Treating the code as the contract: whatever it does today becomes a promise nobody chose.
  • Describing only the successful answers, not the errors.

Follow-up the interviewer might ask:

  • Who should review a contract change? (The people who keep it and, for a public API, someone speaking for its clients.)

L2 (Mid-Level): A client asks for a draft’s id. Predict the answer

What the interviewer is testing: Can you trace a request through the view and the queryset?

Flip to check your answerFold answer back

Perfect answer: read_only lets the GET through: the method is allowed and the client accepts JSON. The view asks listed(), which excludes drafts, for that id, gets nothing, and returns problem(404, ...): status 404, type application/problem+json, and the same body as for an id that does not exist. The client cannot tell a draft from nothing, which is the point: the draft’s existence is not public.

A numbered flow of five cards. 1, GET /api/v1/events/12/, a draft. 2, read_only: GET, accepts JSON, public. 3, listed(): drafts excluded, no row. 4, problem(404): No published event has this id. 5, the same answer as a missing id.
Figure 47.4 — A draft’s id, read by a program.

Behind the scenes:

SELECT ... FROM events_event
WHERE NOT status = 'draft' AND id = 12
-- no row
404 application/problem+json

Code proof: a draft, made and rolled back, and the id 0:

"""A draft's id, read by a partner's program."""
from datetime import timedelta

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

from events.models import Event

start = timezone.now() + timedelta(days=30)
with transaction.atomic():
    draft = Event.objects.create(
        title='Secret plan', starts_at=start,
        ends_at=start + timedelta(hours=2),
        timezone='Europe/London', location='Leeds',
        capacity=10, status=Event.Status.DRAFT)
    client = Client(HTTP_HOST='localhost')
    for address in (f'/api/v1/events/{draft.pk}/',
                    '/api/v1/events/0/'):
        answer = client.get(address)
        print(answer.status_code, answer.json()['detail'])
    transaction.set_rollback(True)
404 No published event has this id.
404 No published event has this id.

Common mistakes:

  • Answering 403 for a draft: that confirms it exists.
  • Starting a view from Event.objects and filtering drafts out in only one of the views.

Follow-up the interviewer might ask:

  • How will the organizer read their own draft? (At /api/v1/my/events/{id}/, with a token, from Chapters 48 to 50.)

L3 (Senior): Defend problem details over your own error format

What the interviewer is testing: Can you weigh a standard against a home-made format?

Flip to check your answerFold answer back

Perfect answer: Every API that invents its error shape makes each client write new error handling. Problem details is a published standard, RFC 9457, with its own media type, so a client, a proxy, or a generic tool knows where to find the status, the kind of problem, and the detail without reading our documentation. It is extensible: Otahque adds field errors for writes without breaking anyone. And it costs one small function. What it does not decide is our wording or our problem types, which we still document. I would use our own format only to match an existing family of APIs that clients already handle.

A numbered flow of five cards. 1, need: errors every client can read. 2, home-made: each API its own shape. 3, RFC 9457: one shape and a media type. 4, extensible: field errors later. 5, revisit only to match an existing API family.
Figure 47.5 — Choosing an error format.

Behind the scenes:

404 {"type": "about:blank", "title": "Not Found", ...}
405 {"type": "about:blank", ..., "detail": "POST ..."}
406 {"type": "about:blank", "title": "Not Acceptable"}

Code proof: the error tests:

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

OK

Common mistakes:

  • Sending the site’s HTML error page to a program that asked for JSON.
  • Making clients parse detail, which is meant for people and may change.

Follow-up the interviewer might ask:

  • When would you give a problem its own type instead of about:blank? (When it means more than the status code, such as “the event is full”; then the type URI names it and its page documents it.)

L4 (Senior): A partner shows a cancelled event as published. Diagnose it

What the interviewer is testing: Can you find a caching bug from the symptom?

Flip to check your answerFold answer back

Perfect answer: The partner’s copy is stale, so first I ask how they decide it is still good. If they send If-None-Match and got 304, our tag did not change when the answer did. That is what happens if the tag comes from version: cancelling saves only the status, and version counts edits. The proof below cancels an event and shows version unchanged while the answer changed. The fix is a tag from the answer itself, a hash of the body, which every change alters; Otahque’s public reads use that, and test_cancelling_changes_the_tag_not_the_version keeps it so. If the partner caches without asking at all, Cache-Control: no-cache already tells them to revalidate.

A numbered flow of five cards. 1, symptom: a cancelled event shown as published. 2, the partner sent If-None-Match and got 304. 3, the tag came from version, which counts edits only. 4, cancel saves status: version unchanged. 5, fix: a tag from the body; a test that cancels.
Figure 47.6 — Diagnosing a stale partner page.

Behind the scenes:

cancel: version 1 -> 1   cancel: body changes
If-None-Match "1"        If-None-Match "3f9a..."
304, stale               200, cancelled

Code proof: an event cancelled, with the tag read before it:

"""Why the version cannot be a public read's ETag."""
from datetime import timedelta

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

from events.models import Event

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, status=Event.Status.PUBLISHED)
    client = Client(HTTP_HOST='localhost')
    address = f'/api/v1/events/{event.pk}/'
    tag, version = client.get(address)['ETag'], event.version
    event.cancel()
    event.refresh_from_db()
    print('version:', version, 'then', event.version)
    answer = client.get(address,
                        headers={'If-None-Match': tag})
    print('with the old tag:', answer.status_code,
          answer.json()['status'])
    transaction.set_rollback(True)
version: 1 then 1
with the old tag: 200 cancelled

Common mistakes:

  • Blaming the partner’s cache before checking what our tag is made of.
  • Fixing it by turning caching off, which costs every partner every request.

Follow-up the interviewer might ask:

  • Why is version still right for the organizer’s view in Chapter 48? (Its fields change only through edits, which are exactly what version counts.)

L5 (Lead): Defend versioning in the path and the “only additions” rule

What the interviewer is testing: Can you plan for change over years, not one release?

Flip to check your answerFold answer back

Perfect answer: Partners build once and update rarely, so the API’s real users are programs we cannot change. The version goes in the path because it is visible in every request, log line, and example, and a new version is simply new addresses that can run beside the old. Within version 1 we only add, and clients must ignore what they do not know, so most changes need no new version. A breaking change, renaming a field or changing its meaning, gets /api/v2/, with version 1 kept for at least six months. The OpenAPI file and its test make “only additions” checkable: a removed field fails test_event_fields_match_the_api. I would revisit the path if Otahque ever served many API versions per resource, where media-type versioning scales better.

A numbered flow of five cards. 1, need: partners we cannot update. 2, the version in the path: visible everywhere. 3, within v1: only additions; clients ignore the unknown. 4, a breaking change: v2 beside v1, six months. 5, a test fails when a field disappears.
Figure 47.7 — Planning for change.

Behind the scenes:

add "room"             v1 (clients ignore it)
rename "location"      v2
places_left -> object  v2

Code proof: the OpenAPI tests, which fail if a field is removed:

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

OK

Common mistakes:

  • Breaking clients by renaming a field “because the new name is clearer”.
  • Promising version 1 forever, with no date to end it.

Follow-up the interviewer might ask:

  • How would you know whether anyone still uses version 1? (Count requests per version in the logs, Chapter 39’s request ids and Chapter 63’s monitoring.)

Next: Chapter 48, DRF serializers and validation, rebuilds these endpoints with Django REST framework against the same tests, and opens the organizer’s own events to writes.

PAGE 006