Spec-driven development, for real
Spec-driven development, for realPart 7
The contract
On this page
New to the short codes like REQ, ADR or AC? See the vocabulary in Part 1, or hover over any code.
In short: The API’s shape is written once, in the Django serializers. drf-spectacular generates an OpenAPI schema from them; a script copies it to the web repository; Orval generates typed hooks and models from it. Nobody types a shape by hand anywhere. Each side has a CI drift gate that fails if the committed copy does not match what it should be generated from. Fields a role may not see are absent from the response and optional in the types.
Part 6 wrote the contract change in words. This part covers block 6, which turns those words into one shape both repositories must follow. The team and product are invented.
Wednesday, 10:20
Tasks T1 to T3 are done on the API. Maya’s colleague Jonas owns the web app, and he is about to build the return screen. In his last job, this was the moment he would open the API code, read the response, and type an interface by hand. Then the API would change, his interface would not, and a field would quietly show as blank.
Here, he does not read the API code at all. He runs one command and gets the types.
Think of it like this: A plug and a socket are made in different factories, but both are built to one published standard. Neither factory measures the other’s product. They both read the standard, and an inspector checks each against it.
The chain
Written once: the serializer
class ReturnSerializer(GatedSerializer):
# REQ-041 AC-1: everyone who can see the return sees the fee
late_fee_minor = serializers.IntegerField(read_only=True)
# AC-4: staff only. Removed before serialisation for other
# roles, so the key is ABSENT, not null (P3)
fee_basis = FeeBasisSerializer(read_only=True)
gated_fields = {"fee_basis": "rentals.view_fee_basis"}
class Meta:
model = Return
fields = ["id", "version", "returned_at", "late_fee_minor", "fee_basis"]
@extend_schema(
summary="Record a return",
responses={200: ReturnSerializer, 404: ErrorEnvelope,
409: ErrorEnvelope, 422: ErrorEnvelope},
)
def post(self, request, pk): ...
Generated: the types
After scripts/export-openapi.sh ../web on the API side and pnpm gen:api on the web side, Jonas has this, without typing a line of it:
/**
* Generated by orval from docs/api/openapi.json
* Do not edit manually.
*/
export interface ReturnRecord {
readonly id: number;
readonly version: number;
readonly returned_at: string;
readonly late_fee_minor: number;
/** Present only for roles allowed to see it. */
readonly fee_basis?: FeeBasis;
}
The same record, two roles
AC-4 said staff see the cost basis and customers do not. The contract makes that structural:
// staff
{ "id": 812, "version": 3, "late_fee_minor": 4500,
"fee_basis": { "hours": 3, "hourly_rate_minor": 1500, "capped": false } }
// customer
{ "id": 812, "version": 3, "late_fee_minor": 4500 }
Important: hiding a field on screen is not security; the data is still in the network tab. The server must leave it out. The web app’s golden rule F1 says it plainly: render exactly what the API returns, and never check the role to decide whether a data field shows.
The drift gates
- API: the committed schema must match the code
CI exports the schema again and compares it. A changed serializer without a re-export fails the build.
uv run manage.py spectacular --file /tmp/openapi.json --validate diff -u docs/api/openapi.json /tmp/openapi.json
- Hand-off: one script copies it across
The API’s export script writes the schema and copies it to the web repository’s snapshot.
scripts/export-openapi.sh ../web
- Web: the generated client must match the snapshot
CI regenerates and fails on any difference. A hand-edited generated file cannot survive.
pnpm gen:api git diff --exit-code -- src/lib/api/generated
- A drift costs a red build, not a bug
The error says exactly what to run. Fixing it takes a minute; finding it in production takes a day.
Under the hood: tools and traps
- drf-spectacular generates OpenAPI from DRF serializers and views;
@extend_schemaadds summaries and every response code.--validatechecks the schema is valid. - Orval generates TanStack Query hooks and TypeScript models. In
orval.config.ts, every request goes through one mutator (apiRequest) that adds auth, the idempotency key and the error envelope. - A real trap, recorded in the config: a global
override.query.useQuery: truein Orval reads like “generate query hooks”, but it is checked before the per-verb default and turns every POST, PATCH and DELETE into a query that fires on mount. The kit’s config carries a comment saying not to set it. - Money siblings. The real API this came from sends each amount with a
<key>_moneysibling saying whether it is net or gross of VAT and where it came from. Ambiguous money is a contract problem, not a UI problem. - A validation matrix can be generated from the input serializers too: every field’s type, bounds and whether unknown keys are refused, with a test that keeps the matrix and the code in step. Optional, but useful once you have many endpoints.
Writes have a contract too
Every write sends If-Match with the version it read. A stale version gets 409: refetch and show again.
An Idempotency-Key on each write means a double-click or a network retry records one return, not two.
Every error is {"error": {"code", "message", "fields"}}. A 422 carries the rule that refused it.
Another company’s return answers 404, not 403. The API never confirms a record exists.
Which step am I on?
- I changed a serializer: Export the schemascripts/export-openapi.sh ../web, commit both repositories’ copies, then pnpm gen:api.
- The UI needs a field that is not there: Change the API firstAdd it to the serializer and spec, export, regenerate. Never add it to a type by hand.
- A role should not see a field: Gate it in the serializerAbsent from the response, optional in the type, proven by a field-security test.
- CI says the client is stale: Regenerate and commitpnpm gen:api, then commit what changed. Do not edit generated files.
In the kit
templates/api/scripts/export-openapi.shand the API CI with the schema drift gate.templates/web/orval.config.tsand the web CI with the client drift gate.- The
new-endpointskill: gated serializer, layered permissions, If-Match, idempotency, the error envelope, tests and the export.
Three rules of thumb
The serializer is the only place a shape is written. Everything else is generated.
The API checks its schema matches its code; the web checks its client matches the schema.
A field a role may not see never reaches the browser. Optional in the type, missing in the JSON.
QuizThe return screen needs the item’s name, but ReturnRecord has no such field. What does Jonas do?
Show the answer
Answer: Ask for it in the API: serializer, spec, export, regenerate
The generated types are the contract. A field added by hand is a field the API never promised, and CI will overwrite it on the next regeneration anyway.
Words in this post:
- OpenAPI schema: a machine-readable description of every endpoint and field.
- drf-spectacular: generates that schema from Django REST Framework code.
- Orval: generates typed TypeScript hooks and models from the schema.
- Drift gate: a CI step that regenerates and fails if the committed copy differs.
- Gated field: a field removed from the response for roles that may not see it.
Next, Part 8: Gates that make Claude show its work stops Claude writing a screen until it has named the exact types it read.
Setting up Claude Code or AI agents for your team?
I help teams build this: agents, RAG search and Claude Code setups that hold up in production.
Series
Spec-driven development, for real
- Spec-driven development, for realThe building blocks
- Spec-driven development, for realThe paper trail
- Spec-driven development, for realPrinciples and scoped rules
- Spec-driven development, for realDecision records
- Spec-driven development, for realDefinitions and open questions
- Spec-driven development, for realFeature specs and plans
- Spec-driven development, for realThe contractyou are here
- Spec-driven development, for realGates that make Claude show its work
- Spec-driven development, for realSkills and reviewers
- Spec-driven development, for realGuardrail hooks
- Spec-driven development, for realProof of done
- Spec-driven development, for realMemory and handoffs
- Spec-driven development, for realOne ticket, end to end