Module 3 · API design

Lesson 15 — Validation and contracts with OpenAPI

Input validation and a contract the client can read without asking you.

Published
In this lesson
  1. Exercise 1 — The serializer with limits
  2. Exercise 2 — The layers in action
  3. Exercise 3 — The living contract
  4. Exercise 4 — The contract as a test
  5. Submit

DRF + pip install drf-spectacular. Do not look at solutions.md before submitting.

Exercise 1 — The serializer with limits

  1. Write the full ReserveInputSerializer (event UUID, seats 1-8 with sector/row/number, optional write_only promo_code).
  2. Test from the shell with serializer.is_valid(): 0 seats, 9 seats, malformed seats, nonexistent uuid. Useful messages in every case?
  3. Add validate_event checking existence (shape/reference) and justify why "past event" (business) goes in the service and not here.

Exercise 2 — The layers in action

  1. Send a POST with malformed JSON, another with wrong types and another with impossible business (seat taken). Document which layer answers each and with which status.
  2. Move (hypothetically) the "seat free" check into the serializer: which race do you reintroduce? (connect it with 10).

Exercise 3 — The living contract

  1. Install drf-spectacular, publish /api/schema/ and /api/docs/. Download the YAML and review what it guessed wrong (undocumented responses, ambiguous request bodies).
  2. Annotate @extend_schema on your 3 most complex endpoints (reserve, webhook, card redeem) with documented request/responses/errors.
  3. Add spectacular --fail-on-warn to the pipeline (or a local script) and make it pass.

Exercise 4 — The contract as a test

  1. Write a test that: calls your reserve endpoint, takes the JSON response and validates that its status/structure matches the schema's declaration (minimum: status code and body keys).
  2. Extract the schema's examples and validate a real response against the example (by hand or with jsonschema). How many times have you seen docs that lie? This test is the vaccine.

Submit

Paste the serializer, the trimmed schema and the CI results. Next: Lesson 16 — gRPC, GraphQL, WebSockets/SSE.