Module 04 · Lesson 4.3
Designing an API Contract
On this page
- What you will learn
- What an API contract is
- The Tidewell contract in OpenAPI
- Consistent errors with problem details
- Step-by-step workflow
- Reviewing a contract with an assistant
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
In a restaurant, the menu is a promise. The kitchen knows what to cook, the waiter knows what to offer and the guest knows what to expect. Nobody has to walk into the kitchen to ask. An API contract is the menu of your backend.
In this lesson you write the contract for Tidewell's booking API before any endpoint exists. You use OpenAPI, a standard format for describing an API, and a standard shape for errors. You also check that the finished code and the contract still agree, and you use an assistant as a reviewer.
What you will learn
- Explain what an API contract is and why it is written before the code.
- Describe an endpoint in OpenAPI, with its request, its success response and its error responses.
- Describe errors in one consistent shape, using problem details.
- Review a contract against your requirements, with an assistant as a second pair of eyes.
Before you start
- Completed Database Schema and Migrations, or have a data model of your own.
- Access to any capable AI assistant.
- Optional: Node.js and the project from earlier lessons, if you want to run the examples.
What an API contract is
An API is a way for one program to ask another for something. A phone app asks your server for free slots. The server answers. A contract is the written agreement about how to ask and what comes back. Both sides build to it, so they can work at the same time.
- Endpoint
- One address on your server that does one job, such as the address that books a slot. It is one item on the menu.
- HTTP method
- The kind of request. GET reads something. POST asks the server to do something, such as create a booking.
- Status code
- A three-digit number in the answer. 200 means it worked. 404 means not found. The first digit tells you the family: 2 worked, 4 the caller needs to change something, 5 the server failed.
- JSON
- A plain-text way to write data, with names and values, such as {"slotId": 12}. Most web APIs use it.
- OpenAPI
- A standard file format for describing an API, written in YAML or JSON. Tools can read it, check it and draw documentation from it.
- Contract-first
- Writing the contract before the code, then building to it. The alternative is to write code and describe it later, which leaves the description to drift.
Writing the contract first has a practical payoff. The screens in Module 5 can be built against it while the backend is still being written. And an assistant given the contract has something real to follow instead of inventing field names.
| Status | Plain meaning | Tidewell use |
|---|---|---|
| 200 OK | It worked. | A booking was cancelled. |
| 201 Created | It worked and made something new. | A booking was created. |
| 400 Bad Request | I cannot understand what you sent. | slotId is missing or is text. |
| 404 Not Found | There is nothing here for you. | No such slot, or not your booking. |
| 409 Conflict | That clashes with the current state. | Someone else just booked the slot. |
| 422 Unprocessable Content | I understood you, but a rule says no. | Too close to the appointment to cancel online. |
| 500 Internal Server Error | Something broke on our side. | The database was unreachable. |
The Tidewell contract in OpenAPI
Tidewell's API has six endpoints. Each one traces to a requirement. The patient is always the signed-in patient. Until sign-in exists in Module 6, the code uses a stand-in that returns test patient 1, and the stand-in is marked for replacement. Staff endpoints for FR-04 arrive with roles.
| Endpoint | Does | Success | Requirement |
|---|---|---|---|
| GET /api/clinicians | Lists active clinicians. | 200 | FR-01 |
| GET /api/clinicians/{clinicianId}/free-slots?date=YYYY-MM-DD | Lists free slots for a day. | 200 | FR-01 |
| GET /api/bookings | Lists the patient's upcoming bookings. | 200 | FR-02 |
| POST /api/bookings | Books a slot. | 201 | FR-01, FR-02 |
| POST /api/bookings/{bookingId}/move | Moves a booking to another slot. | 200 | FR-02 |
| POST /api/bookings/{bookingId}/cancel | Cancels a booking. | 200 | FR-02 |
Cancelling uses POST with an action name, not DELETE. A cancelled booking is kept, with a new status, because FR-05 wants the history. DELETE suggests the record disappears. This lesson writes out two of the six endpoints in full. The other four follow the same pattern.
Create a booking
openapi: 3.1.0
info:
title: Tidewell booking API (excerpt)
version: 0.1.0
paths:
/api/bookings:
post:
operationId: createBooking
summary: Book a free slot for the signed-in patient (FR-01, FR-02).
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [slotId]
properties:
slotId: { type: integer, minimum: 1 }
responses:
"201":
description: The new booking.
content:
application/json:
schema: { $ref: "#/components/schemas/Booking" }
"400": { $ref: "#/components/responses/InvalidRequest" }
"404": { $ref: "#/components/responses/NotFound" }
"409": { $ref: "#/components/responses/SlotTaken" }
"500": { $ref: "#/components/responses/InternalError" }openapi: 3.1.0names the version of the format. Check the current specification when you write your own.pathslists the addresses. Under each address come the methods, herepost.operationIdis a unique name for the action. Tools use it to name generated functions.requestBodysays what the caller sends.required: [slotId]makes the field compulsory andminimum: 1rejects zero and negatives.responseslists every status code the caller can get. The 400, 404, 409 and 500 entries point to shared descriptions with$ref, like a reference to a form kept in one place.
Cancel a booking
/api/bookings/{bookingId}/cancel:
post:
operationId: cancelBooking
summary: Cancel one of the signed-in patient's bookings (FR-02).
parameters:
- name: bookingId
in: path
required: true
schema: { type: integer, minimum: 1 }
responses:
"200":
description: The booking, now with status cancelled.
content:
application/json:
schema: { $ref: "#/components/schemas/Booking" }
"400": { $ref: "#/components/responses/InvalidRequest" }
"404": { $ref: "#/components/responses/NotFound" }
"422": { $ref: "#/components/responses/NoticePeriod" }
"500": { $ref: "#/components/responses/InternalError" }The booking id travels in the address, so it is a path parameter. Notice the 422 response: it is documented because the practice manager's 24-hour rule is part of the behaviour. The decision was confirmed after Module 1: a patient may move or cancel online only if the appointment starts at least 24 hours from now, and exactly 24 hours counts as allowed.
Shared pieces: the booking and the problem
components:
schemas:
Booking:
type: object
required: [bookingId, slotId, clinicianName, startsAt, endsAt, status]
properties:
bookingId: { type: integer }
slotId: { type: integer }
clinicianName: { type: string }
startsAt: { type: string, format: date-time }
endsAt: { type: string, format: date-time }
status: { type: string, enum: [booked, cancelled] }
Problem:
type: object
required: [type, title, status, detail]
properties:
type: { type: string, format: uri }
title: { type: string }
status: { type: integer }
detail: { type: string }
errors:
type: array
description: Only for 400 invalid-request.
items:
type: object
required: [field, message]
properties:
field: { type: string }
message: { type: string }The Booking shape is defined once and reused by every endpoint that returns a booking. The Problem shape is the single format for all errors. The file also holds one shared description for each error, like this pair.
responses:
InvalidRequest:
description: The request is malformed (invalid-request).
content:
application/problem+json:
schema: { $ref: "#/components/schemas/Problem" }
NotFound:
description: No such slot or booking, or not yours (not-found).
content:
application/problem+json:
schema: { $ref: "#/components/schemas/Problem" }Consistent errors with problem details
If every endpoint reports errors in its own style, every screen needs its own error code. RFC 9457, the standard for problem details, gives one shape. The content type is application/problem+json, and the body has a few fixed fields.
type: a stable name for this kind of problem. Tidewell uses addresses such as https://tidewell.example/problems/slot-taken. It is a name first. It does not have to open a web page.title: a short, fixed sentence about the kind of problem.status: the same number as the HTTP status code.detail: a sentence for this case, written for a person.errors: an optional list of field problems, used only for 400 invalid-request.
| Code | Status | When | What the person is told |
|---|---|---|---|
| invalid-request | 400 | The body or a parameter is malformed. | Which field is wrong, and how. |
| not-found | 404 | No such slot or booking, or it belongs to someone else. | 'We could not find that.' Nothing more. |
| slot-taken | 409 | A live booking already holds the slot. | Choose another time. |
| notice-period | 422 | The appointment is less than 24 hours away. | Phone 01632 960 123, Monday to Friday, 8:00 to 18:00. |
| internal-error | 500 | Anything unexpected. | A short reference id, and nothing about the cause. |
Here are two real bodies produced by the Tidewell code in the next lesson, both sent with the content type application/problem+json.
{"type":"https://tidewell.example/problems/slot-taken","title":"Slot already taken","status":409,"detail":"Someone else has just booked this slot. Please choose another time."}{"type":"https://tidewell.example/problems/invalid-request","title":"Invalid request","status":400,"detail":"The request has problems. See errors for details.","errors":[{"field":"slotId","message":"slotId must be a whole number above zero."}]}Step-by-step workflow
Step 1: List one action per scenario
Read your acceptance scenarios. Each user action, such as 'cancel a booking', becomes a candidate endpoint.
What you should see: A list of actions with requirement IDs.
Step 2: Name the endpoints
Use nouns in the path (bookings) and a method for the verb. For an action that changes state without deleting, use an action name like cancel.
What you should see: A table of method, path and purpose.
Step 3: Write the request and the success response
Write the fields, their types and their limits. Reuse a shared shape for anything returned in several places.
What you should see: A schema for each request and response body.
Step 4: Write every error response
For each scenario that ends in a refusal, add a status code. Use one shared problem shape for all of them.
What you should see: Every acceptance scenario that fails has a documented status code.
Step 5: Review with an assistant
Use the prompt card. Take its findings to the requirements, and keep or reject each one.
What you should see: A reviewed contract and a short list of decisions.
Step 6: Save the contract and keep it true
Save it as docs/api/openapi.yaml with the date. When the code changes, change the contract in the same commit.
What you should see: A contract that matches the code on every commit.
- Scenarios
One action each
- Endpoints
Method and path
- Schemas
Request and response
- Errors
One problem shape
- Review
Assistant, then you
- Code and test
Built to the file
The contract sits between the requirements and the code, and a test keeps it honest.
Checking that the code and the contract agree
A contract that nobody checks goes out of date. The test below reads the YAML file, creates a real booking through the Tidewell code and compares the field names. It then collects every status code the code produced and compares them with the ones the contract lists.
const created = await handleCreateBooking(post('{"slotId":3}'), deps);
const booking = (await created.json()) as Record<string, unknown>;
const bookingSchema = spec.components.schemas.Booking;
console.log("Booking keys match contract:", JSON.stringify(Object.keys(booking).sort()) === JSON.stringify(Object.keys(bookingSchema.properties).sort()));
console.log("all required present:", bookingSchema.required.every((k) => k in booking));const observed = new Set<string>();
const note = (r: Response) => observed.add(String(r.status));
note(created);
note(await handleCreateBooking(post('{"slotId":"x"}'), deps));
note(await handleCreateBooking(post('{"slotId":3}'), deps));
note(await handleCreateBooking(post('{"slotId":999}'), deps));
note(await handleCreateBooking(post('{"slotId":3}'), { ...deps, db: { query: async () => { throw new Error("x"); } } }));
const listed = Object.keys(spec.paths["/api/bookings"].post.responses).sort();
console.log("POST /api/bookings documented:", listed.join(","), "| observed:", [...observed].sort().join(","));Booking keys match contract: true
all required present: true
POST /api/bookings documented: 201,400,404,409,500 | observed: 201,400,404,409,500Both checks pass. Had the code returned a status the file did not list, or dropped a field, the lines would differ. A check like this is a cheap way to stop drift. For a bigger project, tools can validate a contract file or generate TypeScript types from it, for example openapi-typescript.
Reviewing a contract with an assistant
An assistant is good at spotting gaps in a contract: a missing error response, a field with no limit, a name that does not match the others. It is poor at knowing what your clinic wants, so it needs your requirements next to the contract.
| Task | Assistant's part | Your part |
|---|---|---|
| Draft the file | Writes OpenAPI from your endpoint table. | Check each path and field against the requirements. |
| Find gaps | Lists missing responses and unclear fields. | Decide which gaps are real. |
| Check consistency | Compares names, formats and status codes. | Pick one convention and keep it. |
| Propose extras | Adds endpoints such as 'list all patients'. | Reject anything with no requirement or permission rule. |
| Choose behaviour | Nothing. It guesses. | Decide notice periods, who sees what and what 404 means. |
Conclusion and your next step
The API contract is a promise that both sides can read. Write it before the code, describe every success and every error, use one shape for problems and keep a test that compares the file with the real behaviour.
Your next step: write the contract for two endpoints of your capstone, with every error response, and ask an assistant to find gaps. Then continue to Implementing Endpoints with Validation, where you build the booking endpoints to this contract.
To go further, read API-First Development: OpenAPI Contracts with AI and try the Appointment Booking Portal project.
Reusable prompt
API contract review
Reviews an endpoint list and error format against requirements, and reports gaps and extras without adding endpoints itself.
You are reviewing an API contract. Do not add endpoints and do not write code. Report findings only.
Fictional clinic: Tidewell Physiotherapy. Out of scope: payments, insurer billing, clinical notes.
Requirements:
FR-01 A patient can see the free slots for a chosen clinician and date.
FR-02 A patient can move or cancel their own booking without calling the clinic.
FR-05 Every change to a booking records who made it and when.
Rule (confirmed by the practice manager): online move or cancel only if the appointment starts at least 24 hours from now. Exactly 24 hours is allowed.
Rule: a patient must not learn whether another patient's booking exists.
Endpoints:
POST /api/bookings { slotId } -> 201 booking
POST /api/bookings/{bookingId}/cancel -> 200 booking
Errors use the problem details format (400 invalid-request, 404 not-found, 409 slot-taken, 422 notice-period, 500 internal-error).
Tasks:
1. List responses or cases that are missing, each with the requirement it relates to.
2. List fields without a type, a limit or a format.
3. List inconsistencies in naming, status codes or error shapes.
4. List anything that could reveal information to the wrong person.
5. List questions for the client that the contract cannot answer. Do not answer them yourself.Show the reusable template
Replace each {{placeholder}} with your own details.
You are reviewing an API contract. Do not add endpoints and do not write code. Report findings only.
Context: {{organisation_and_scope}}.
Requirements and rules:
{{requirements_and_confirmed_rules}}
Endpoints:
{{endpoints_and_responses}}
Errors use {{error_format}}.
Tasks:
1. List responses or cases that are missing, each with the requirement it relates to.
2. List fields without a type, a limit or a format.
3. List inconsistencies in naming, status codes or error shapes.
4. List anything that could reveal information to the wrong person.
5. List questions for the client that the contract cannot answer. Do not answer them yourself.Expected output and limitations
A findings list grouped by the five tasks: missing cases, untyped fields, inconsistencies, possible information leaks and open questions. Each finding names the requirement or line it relates to.
1. Missing cases
- POST /api/bookings has no response for a slot that has already started (FR-01).
2. Fields without limits
- The bookingId path parameter has no upper limit, so a huge number is accepted.
3. Inconsistencies
- The 404 description for bookings says "not yours", the one for slots does not.
4. Possible leaks
- If a booking id that exists but belongs to someone else returned 403, it would reveal that it exists. Keep 404.
5. Questions for the client
- What should a patient see if their appointment is cancelled by the clinic?Limitations to keep in mind
- It reviews what is written. It cannot see requirements you did not paste, so gaps against hidden requirements stay hidden.
- Some findings will be wrong or already handled. Check each against the file before acting.
- It may suggest new endpoints despite the instruction. Reject any that has no requirement and permission rule.
Common errors and how to fix them
The contract describes only the success response.
Why it happens: The happy path was written first and the refusals were never added.
Fix: Add a response for every scenario that ends in a refusal. Use the acceptance criteria as the list.
Each endpoint reports errors in a different shape.
Why it happens: Errors were written endpoint by endpoint, with no shared format.
Fix: Define one Problem schema and reference it from every error response.
The contract and the code have drifted apart.
Why it happens: The code was changed and the file was not.
Fix: Change both in one commit, and run a check that compares field names and status codes.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
A contract for recording parts at Ferngate
Write an OpenAPI description for the Ferngate endpoint that records a part taken for a job. Include the request, the success response and every error response, then run the API contract review prompt on it.
You will need
- Requirement: a mechanic can record a part taken for a job.
- Note: mechanics share one tablet, and the connection is unreliable, so the same request may be sent twice.
- Note: the owner has not decided what should happen when a mechanic records a part the system thinks is out of stock.
Acceptance criteria
Your work is done when every one of these is true.
Hints (2)
- A request sent twice because of a bad connection should not take two parts. Decide how the caller can make that safe.
- A part id that does not exist is a different problem from a quantity of zero.
Show a model answer
A strong answer uses POST on a path under the job, with partId and quantity limited to whole numbers above zero, and a 201 response that returns the new record. It lists 400 for a malformed body, 404 for an unknown job or part, and a shared problem shape for both. The out-of-stock case is written as 'Decision needed: owner' because blocking, warning and allowing each change how the workshop runs. A repeated request needs a stated rule, such as a caller-chosen request id that the server remembers. An assistant's suggested 'delete all movements for a job' endpoint is rejected because no requirement asks for it.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. A written contract gives both sides the same names, types and errors. Guessing is tempting because it feels fast, but each wrong guess becomes rework when the real code arrives.
Show the answer and explanation
Answer: B. A 403 confirms that the booking exists, which leaks information that FR-02.3 says must stay private. 403 is the tempting answer because it describes the situation accurately, but accuracy is not the goal here. A 200 would wrongly say it worked.
Show the answer and explanation
Answer: B. Text instead of a number is a malformed request, so 400. A well-formed request refused by the notice-period rule is 422. Using 400 for both is tempting and not wrong everywhere, but it hides a useful difference between 'fix your request' and 'a rule says no'.
Frequently asked questions
What is an API contract in simple terms?
It is a written agreement about how programs talk to each other: which addresses exist, what to send and what comes back, including errors. It works like a menu. Both sides can read it, so they can build separately and still fit together.
What is OpenAPI, and do I need to learn YAML?
OpenAPI is a standard format for describing a web API. It is usually written in YAML, a plain-text format that uses indentation, and you only need a few patterns to read it. Many tools can check it, draw documentation from it and generate code types.
What is the difference between a 400 and a 422 status code?
A 400 means the request itself is malformed, such as a missing field or text where a number belongs. A 422 means the request is well formed, but a rule refuses it, such as cancelling too late. Using both lets the caller know whether to fix the request or accept the rule.
Can AI write my OpenAPI file?
It can draft one from your endpoint list in seconds. It may add endpoints and fields you did not ask for, so check every path against a requirement. Treat the draft as a starting point and keep the decisions with you.
- Written by
- PromptFable Editorial
- Last updated 19 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- OpenAPI Specification(opens in a new tab)
OpenAPI Initiative · Official documentation · The full specification of the description format used in this lesson.
- RFC 9457: Problem Details for HTTP APIs(opens in a new tab)
IETF · Official documentation · The standard behind the application/problem+json error shape.
- HTTP response status codes(opens in a new tab)
MDN Web Docs · A plain reference for what each status code means.
- Route Handlers(opens in a new tab)
Next.js · Official documentation · How Next.js route handlers receive a Request and return a Response. Check the current version of the docs.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.