Skip to content
zeeshare.com

writing / FDE and agents

Spec-driven development, for real

Spec-driven development, for realPart 7

The contract

On this page
  1. Wednesday, 10:20
  2. The chain
  3. Written once: the serializer
  4. Generated: the types
  5. The same record, two roles
  6. The drift gates
  7. Writes have a contract too
  8. Which step am I on?
  9. In the kit
  10. Three rules of thumb

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.

API side Web side CI drift gates Field security Claude

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

API repository serializer drf-spectacular openapi.json CI: matches code? Web repository openapi.json copy pnpm gen:api generated types CI: matches copy? Nobody types an API shape by hand, anywhere.
One shape, written once in the serializer, generated everywhere else. Each side has a gate that fails if it drifts.

Written once: the serializer

src/rentals/api/serializers.py
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): ...
The serializer is the single source. The schema, the types and the docs are generated from it.

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:

src/lib/api/generated/model/returnRecord.ts (generated, never edited)
/**
 * 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;
}
fee_basis is optional in the type because some roles never receive it. That is the field-security contract, written into the types.

The same record, two roles

AC-4 said staff see the cost basis and customers do not. The contract makes that structural:

the same return, two roles
// 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 }
The customer’s response has no fee_basis key at all. There is nothing to hide on screen, because it never arrived.

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

  1. 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
  2. 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
  3. 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
  4. 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_schema adds summaries and every response code. --validate checks 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: true in 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>_money sibling 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

Writes carry a version

Every write sends If-Match with the version it read. A stale version gets 409: refetch and show again.

Retries have one effect

An Idempotency-Key on each write means a double-click or a network retry records one return, not two.

One error shape

Every error is {"error": {"code", "message", "fields"}}. A 422 carries the rule that refused it.

Missing means 404

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

Three rules of thumb

Written once

The serializer is the only place a shape is written. Everything else is generated.

Gated both sides

The API checks its schema matches its code; the web checks its client matches the schema.

Absent, not hidden

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.

See services
Next in this seriesSpec-driven development, for realGates that make Claude show its work4 min read