Choose the right status code and error code for success, invalid input, missing credentials, missing or other users' resources, and conflicts.
Write an OpenAPI 3.1 operation with a request body and every response, reusing shared schemas and responses.
Implement an endpoint that follows a contract written before the code.
Verify a contract by sending a request for each documented response and comparing status, code and body shape.
Review an agent's contract draft for invented status codes, inconsistent error shapes and missing outcomes.
Prerequisites
Comfortable reading TypeScript and SQL.
Can send HTTP requests with curl and read JSON responses.
Has added an endpoint to an existing service, for example in the lesson Implement a scoped feature.
Concepts
A contract is a promise about every outcome
An API contract describes what a client may send and every response it can get back: the success case, and each way the request can fail. The failure cases matter as much as the success case, because they are what client code has to branch on. A mobile app that books a meeting room needs to know whether a refusal means "fix your input", "sign in again", "that booking is gone" or "someone else took the slot", and it can only know that if the API says so consistently.
Designing the contract first means writing those outcomes down before writing the handler. It forces the questions that are easy to skip in code: what happens if the body has an unknown field, if the booking belongs to someone else, if it was cancelled yesterday? Answering them on paper is cheap. Discovering them in production, after clients have started depending on whatever the code happened to do, is not.
Status codes carry the category, error codes carry the reason
HTTP status codes (RFC 9110 (opens in a new tab)) say which kind of outcome occurred. The booking service uses a small, deliberate set:
Status
Meaning in this API
Example
200
The request succeeded and the body holds the result
Reading or changing a booking
201
Worked example
The situation
A partner team wants to show free meeting-room times in their own app, so they ask for the contract of the availability endpoint, GET /resources/{id}/availability. You ask an agent to write the OpenAPI operation for it. This walk-through shows how to review and verify what comes back. It uses an existing endpoint on purpose: when you document behaviour that already exists, the running service is the source of truth and the contract must match it. When you design something new, as in the exercise, the contract comes first and the code must match it. The verification technique is the same in both directions.
Step 1: list the outcomes before reading the draft
Before looking at the agent's YAML, read the handler in src/routes/resources.ts and write down every way a request can end. This takes five minutes and gives you something independent to compare the draft against.
Condition
Expected status and code
Valid request
200 with data.windows
from or to missing or not a date-time
400 VALIDATION_FAILED (the Fastify schema)
Concept questions
Sign in and enrol to answer and save your progress.
Exercise
Your task
Users can book a resource but cannot move a booking. Add rescheduling: PATCH /bookings/{id} changes the start and end of one of the caller's bookings. Design it in openapi.yaml first, then implement it so the service does exactly what the contract says.
The behaviour to design and build:
The body is { "starts_at": "…", "ends_at": "…" }. Both fields are required and no other fields are accepted (so resource_id cannot be changed).
The new period follows the same rules as creating a booking (future start, at most 12 hours, slot boundaries, opening hours in the resource's time zone), and the price is recalculated for the new period.
The new period may overlap the booking's own current time (moving a booking 30 minutes later is fine), but not any other confirmed booking of the resource.
Responses:
200 with the updated booking, in the same shape as GET /bookings/{id};
400 with VALIDATION_FAILED or the booking-rule codes (INVALID_PERIOD, INVALID_SLOT, STARTS_IN_PAST, );
Reflection
Recorded for you to look back on. It is not graded and does not by itself show understanding.
Prompt: What did your contract have to decide that the task left open, such as which check wins when a request breaks two rules? When you checked the running service against the contract, did anything differ, and did you change the code or the contract? Explain why.
The request itself is invalid; sending it again unchanged will fail again
VALIDATION_FAILED, INVALID_SLOT, STARTS_IN_PAST
401
No valid credentials
Missing or unknown bearer token
404
The target does not exist for this caller
BOOKING_NOT_FOUND for an unknown id or someone else's booking
409
The request is valid but conflicts with the current state
SLOT_UNAVAILABLE
Two choices in this table deserve a closer look.
400 or 422. Many APIs separate malformed requests (400) from requests that are well formed but semantically unacceptable (422 Unprocessable Content), such as a booking that starts in the past. Both conventions are defensible. This service uses 400 for every invalid input and distinguishes the cases by error code. What matters is that the rule is applied everywhere: a client should never have to guess which status a new endpoint picked.
404 for "not yours". Answering 403 for another user's booking would confirm that the booking exists. RFC 9110 explicitly allows a server to respond 404 when it "is not willing to disclose that one exists". This API does exactly that, so an unknown id and someone else's id are indistinguishable.
The line between 400 and 409 is whether the request could succeed in a different state of the world. Overlapping a confirmed booking is a 409: the same request would succeed if that booking were cancelled. A booking outside opening hours is a 400: no state change will make it valid.
A stable error envelope
Every error in this service has the same shape:
{ "error": { "code": "SLOT_UNAVAILABLE", "message": "That time overlaps an existing booking" } }
The code is the stable, machine-readable part; clients branch on it. The message is for humans and may change. An optional details field carries structured extras, such as the failed schema rules for VALIDATION_FAILED. Problem Details (RFC 9457 (opens in a new tab)) is a standard alternative with the same idea. Whichever envelope an API uses, every endpoint must use it, including for errors the framework raises, such as schema validation failures. In this service, src/app.ts converts those into the envelope centrally.
OpenAPI as the written contract
OpenAPI 3.1 describes an HTTP API in YAML or JSON. Under paths, each operation (get, post, patch, …) lists its parameters, its requestBody and its responses by status code. Reusable parts live under components and are referenced with $ref: in this service's openapi.yaml, the Error schema, the Booking schema and shared responses such as BookingNotFound are defined once and reused by every endpoint. A request schema with required fields and additionalProperties: false documents, and can enforce, that unknown fields are refused.
An OpenAPI document is only as true as its last check against the running service. It can parse cleanly and still describe responses the code never sends. Validating the YAML proves its shape, not its accuracy.
Using an agent for contract work
Agents are good at producing plausible OpenAPI quickly, and that is the risk: plausible is not the same as true. Work in two separate steps.
Ask for the contract alone. Point the agent at openapi.yaml, the README and the route you are changing, and ask it to add the operation without touching code. Ask it to reuse existing components and to list each response with the condition that triggers it. Then review the list yourself: is every failure mode there, and is each one in the right category?
Then implement against the contract. Ask for the handler and for tests that cover each documented response, not only the happy path.
Typical agent mistakes here are predictable. Agents introduce status codes the API does not use (403 for "not yours", 422 for rule violations), write a separate error shape for the new endpoint, forget that the overlap check must ignore the booking being changed, and document responses that the implementation never produces. They also tend to write tests that agree with their own implementation, so a passing suite says less than it seems to.
The check that matters is behavioural: for each response in the contract, send a request that should produce it and compare the status, the error code and the body shape with what the contract promises. Do that yourself, with curl or a test, before you trust the agent's summary.
min_minutes outside 1 to 1440
400 VALIDATION_FAILED
to not after from, or a range longer than 3660 days
400 INVALID_RANGE
id not a positive integer
400 VALIDATION_FAILED (the path schema)
No resource with that id
404 RESOURCE_NOT_FOUND
The endpoint needs no token, so there is no 401.
Step 2: review the draft against the list
Suppose the agent's draft contains this (shortened):
Compared with the list from step 1, it has four problems:
Wrong status. The service answers 400 INVALID_RANGE, not 422. The agent used a common convention instead of this API's.
Wrong error shape. The schema describes { "message": … } instead of reusing components/schemas/Error. A client generated from this contract would fail to read every error.
Invented limit.maximum: 10080 is not in the code; the query schema says 1440.
Missing outcomes. There is no 404 and no VALIDATION_FAILED.
None of these would be caught by validating the YAML: the document is well formed. They are only visible when you compare it with behaviour.
Step 3: verify each outcome against the running service
Start the service (npm run db:reset, then npm start) and send one request per row of the table. -w prints the status after the body.
The output (messages shortened) confirms the table, not the draft:
{"data":{"resource_id":3,"from":"…","to":"…","windows":[{"starts_at":"…","ends_at":"…","minutes":1440}]}} 200
{"error":{"code":"VALIDATION_FAILED","message":"querystring must have required property 'to'","details":[…]}} 400
{"error":{"code":"VALIDATION_FAILED","message":"querystring/min_minutes must be <= 1440","details":[…]}} 400
{"error":{"code":"INVALID_RANGE","message":"to must be after from"}} 400
{"error":{"code":"RESOURCE_NOT_FOUND","message":"Resource 999 does not exist"}} 404
Every error uses the same envelope, including the ones Fastify raised, because src/app.ts converts them centrally. That is worth knowing when you add an endpoint: if you declare a schema on the route, malformed input already becomes 400 VALIDATION_FAILED in the right shape.
Step 4: correct the contract and keep it honest
Here the code is the source of truth, so the contract changes: 400 with both codes named in its description, 404 reusing components/responses/ResourceNotFound, maximum: 1440, and every error body as $ref: "#/components/schemas/Error". The starter's openapi.yaml shows the finished version.
To keep it true, turn the curl session into tests. One test per documented outcome, each asserting the status, error.code and the presence of error.message, will fail the next time someone changes behaviour without changing the contract.
What to take into the exercise
Write the list of outcomes yourself before you read an agent's draft.
Check status, error code and body shape for each documented response, not just the success case.
Reuse the shared components so new endpoints cannot drift from the envelope.
When designing something new, settle the contract first, then make the code meet it, and verify in the same way.
OUTSIDE_OPENING_HOURS
401 without a valid token;
404 BOOKING_NOT_FOUND when the booking does not exist or belongs to someone else;
409 SLOT_UNAVAILABLE when the new period overlaps another confirmed booking, and 409 BOOKING_CANCELLED when the booking has been cancelled.
Steps
Read the starting point.openapi.yaml documents the existing endpoints accurately; README.md summarises them. Read POST /bookings and GET /bookings/{id} in both the contract and src/routes/bookings.ts.
Write the contract. Add a patch operation under paths./bookings/{id} with a requestBody and every response listed above. Reuse what exists: the BookingId parameter, the Booking and Error schemas, and responses such as BookingNotFound and Unauthenticated. Where one status has several codes, name them in the description. Decide, and write down, which check wins when a request breaks more than one rule (for example, a cancelled booking moved outside opening hours).
Review the contract before any code exists. If an agent drafted it, compare it with the list above yourself. Look for status codes this API does not use, a new error shape, or a missing 404.
Implement it in src/routes/bookings.ts. Keep the existing style: a route schema for the body, requireUser, the transaction() helper and the error helpers in src/errors.ts.
Test every documented response. Add tests under test/ for success and for each failure. A cancelled booking can be set up directly in a test, because useTestApp() also returns the database pool:
const { app, db } = useTestApp();
// after creating a booking with POST /bookings:
await db().query("UPDATE bookings SET status = 'CANCELLED', cancelled_at = now() WHERE id = $1", [id]);
Verify against the running service, not only the tests:
npm run verify # type check and tests
npm run db:reset && npm start
In another terminal, book something and move it. dev-token-ada and dev-token-grace are seeded users; resource 3 has one-hour slots and is open all day (UTC).
Replace ID with the id from the first response. Then try the same PATCH with dev-token-grace, with an extra field, with a period that overlaps another booking, and against a booking id that does not exist. Compare each answer with your contract.
Constraints
Do not change package.json or package-lock.json, and do not add dependencies. The assessment starts your service with the starter's pinned dependencies; a changed lockfile means it is not started.
Do not edit db/migrations/001_init.sql. If you need a schema change (this task should not), add a new migration file.
Keep the existing endpoints and their responses working, and keep GET /health, DATABASE_URL and PORT as they are.
Keep openapi.yaml valid OpenAPI 3.1 at the repository root.
How Check work assesses this
When you select Check work, the platform takes a snapshot of your workspace's source files and assesses it outside the lab. Your service is started with node src/server.ts against a fresh database with its own test data, and the checks call it over HTTP as a client would, with two different users. openapi.yaml is read from the snapshot. Nothing printed in the lab and no change to the tests in test/ affects the result; your tests are for you, so you know the answer before you check.
The checks verify the behaviour of PATCH /bookings/{id} for success, invalid requests, missing and other users' bookings, and conflicts. The contract check is structural: it confirms that openapi.yaml documents the operation with a request body and 200, 400, 404 and 409 responses. It cannot tell whether your descriptions are accurate; that part is your review.
Tools
You can do this exercise with any compatible tool in the lab. With an agent, try asking for the contract change on its own first, review it, and only then ask for the implementation and tests.
Acceptance criteria
AC1Rescheduling your own booking returns 200 with the new times and the recalculated price.Verified behaviour
AC2Invalid requests are refused with 400 and the standard error format.Verified behaviour
AC3A booking that does not exist, or belongs to someone else, returns 404 BOOKING_NOT_FOUND.Verified behaviour
AC4Conflicts return 409 with a specific code: SLOT_UNAVAILABLE or BOOKING_CANCELLED.Verified behaviour
AC5openapi.yaml documents PATCH /bookings/{id} with its request body and its 200, 400, 404 and 409 responses.Structure check
Verified behaviour is checked by running your submitted work from outside the lab. A structure check confirms that something is present and in the expected format; it does not prove it is correct.
Not assessed
Whether the descriptions, examples and schemas in openapi.yaml are accurate; the contract check confirms only that the operation and its responses are present.
The wording of error messages; clients are expected to rely on the error code, not the message.
Two reschedules racing for the same slot at the same moment; the lesson Prevent double bookings covers concurrency.
The tests you add under test/; the assessment runs its own checks instead.
Code structure and readability.
Hints
Try the exercise first. Each hint gives away a little more than the one before.
Check your work
Submit your work from the lab's Check work panel. Hidden checks run your submitted code from outside the lab; your own test output is never taken as a result. You can revise and resubmit.
GitHub's open source toolkit that gives AI coding agents structured processes, starting with spec-driven development from specification to plan, tasks and code.