Module 08 · Lesson 8.2
API and Architecture Documentation
On this page
- What you will learn
- Why API and architecture documents go stale
- Keep the API contract true with a drift check
- Keep decision records and diagrams true
- Make 'docs updated' part of the definition of done
- Step-by-step workflow: keep the documents true
- What the assistant does and what you do
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Imagine a road map printed ten years ago. It looks neat, and it sends you to a bridge that is gone. A wrong document is worse than no document, because people trust it. API and architecture documents go wrong in exactly this way, and a fast assistant makes it happen faster.
In this lesson you keep Tidewell's documents true. You make the API contract the source of truth and run a small script that compares it with the routes the code really serves. You learn to mark a decision record as superseded instead of rewriting it. You update diagrams in the same change as the code. And you make 'docs updated' part of the definition of done.
What you will learn
- Explain why documents go stale and what a source of truth is.
- Run a drift check that compares the routes the code serves with
openapi.yaml. - Change a decision record's status and update diagrams without rewriting history.
- Add 'docs updated' to the definition of done, and decide with a person whether the code or the document is right.
Before you start
- Completed README and Operating Notes, or have a README 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.
Why API and architecture documents go stale
A document goes stale when the thing it describes changes and the document does not. Nobody decides to let that happen. A route is renamed on a busy afternoon, a new box appears in the design, and the text stays as it was.
The fix is not to write more. It is to give each document one source of truth, and to check that the rest agrees with it. A source of truth is the one place where the answer is kept, like the master copy of a recipe that every cook copies from.
- Source of truth
- The one document or file that is right when two places disagree.
- API contract
- The written promise of what the API accepts and returns. Tidewell's lives in
docs/api/openapi.yaml, from Designing an API Contract. - Drift
- The slow gap that opens between a document and the thing it describes, like a clock that loses a minute a week.
- Superseded
- Replaced by a newer decision. The old record stays, marked as superseded, as in Architecture Decision Records.
| Document | Source of truth | What keeps it true |
|---|---|---|
| API contract | docs/api/openapi.yaml | A contract test of the responses and a drift check of the routes, both run in the pipeline. |
| Decision records | docs/adr/ | A status change, not a rewrite. A new record when a decision changes. |
| Diagrams | Mermaid text in docs/architecture.md | Updated in the same pull request as the change that alters the design. |
| README and operating notes | The project itself | A docs checker and a fresh-eyes run, from the last lesson. |
| Every document | The definition of done | A change is not finished until the documents it touches are updated. |
Keep the API contract true with a drift check
In Module 4 you wrote the contract first and then built to it. A test checked that the real responses matched the contract's fields and status codes. That test cannot see a route that is missing from the contract, because nothing ever calls it. A drift check closes that gap. It lists the routes the code serves, lists the paths in the contract, and reports every difference.
In a Next.js project, each route is a file named route.ts. The folder path is the URL, and a folder in square brackets is a path parameter. This is the Tidewell tree. Next.js route files are a tool-specific convention, so check the Next.js route handlers guide (opens in a new tab) for your version.
src/app/api/bookings/[bookingId]/cancel/route.ts
src/app/api/bookings/[bookingId]/move/route.ts
src/app/api/bookings/route.ts
src/app/api/clinicians/[clinicianId]/free-slots/route.ts
src/app/api/clinicians/route.tsThe route files in the example project. Each one exports functions named after HTTP methods, such as GET or POST.
// scripts/check-api-drift.ts: do the routes the code serves match the paths in openapi.yaml?
import { readdirSync, readFileSync } from "node:fs";
import { join, relative, sep } from "node:path";
import { parse } from "yaml";
const METHODS = ["get", "post", "put", "patch", "delete"];
/** Next.js route files: src/app/api/<path>/route.ts, with [id] folders for path parameters. */
export function servedOperations(apiDir: string): string[] {
const found: string[] = [];
const walk = (dir: string) => {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) walk(full);
else if (entry.name === "route.ts") {
const segments = relative(apiDir, dir).split(sep).filter((s) => s !== "" && !/^\(.*\)$/.test(s));
const path = "/api/" + segments.map((s) => s.replace(/^\[(.+)\]$/, "{$1}")).join("/");
const source = readFileSync(full, "utf8");
for (const m of source.matchAll(/export (?:async function|const) (GET|POST|PUT|PATCH|DELETE)\b/g)) {
found.push(`${m[1]} ${path.replace(/\/$/, "")}`);
}
}
}
};
walk(apiDir);
return found.sort();
}
export function documentedOperations(openapiText: string): string[] {
const spec = parse(openapiText) as { paths: Record<string, Record<string, unknown>> };
return Object.entries(spec.paths)
.flatMap(([path, item]) => Object.keys(item).filter((k) => METHODS.includes(k)).map((m) => `${m.toUpperCase()} ${path}`))
.sort();
}
export function findDrift(served: string[], documented: string[]) {
return {
undocumented: served.filter((op) => !documented.includes(op)),
unserved: documented.filter((op) => !served.includes(op)),
};
}
if (process.argv[1] && import.meta.filename === process.argv[1]) {
const served = servedOperations("src/app/api");
const documented = documentedOperations(readFileSync("docs/api/openapi.yaml", "utf8"));
const { undocumented, unserved } = findDrift(served, documented);
if (undocumented.length === 0 && unserved.length === 0) {
console.log(`No drift: ${served.length} operations are both served and documented.`);
} else {
for (const op of undocumented) console.log(`Served but not documented: ${op}`);
for (const op of unserved) console.log(`Documented but not served: ${op}`);
process.exitCode = 1;
}
}Tested with the TypeScript compiler and run below. It reads the paths and methods, not the response shapes.
What each part does
servedOperationswalks thesrc/app/apifolder. For eachroute.tsit turns the folder path into a URL, such as/api/bookings/{bookingId}/cancel, and reads which methods the file exports.documentedOperationsreadsopenapi.yamlwith theyamlpackage and lists each path with each method.findDriftcompares the two lists in both directions. One list holds routes with no documentation. The other holds documented routes that the code does not serve.- The last block runs only when you start the file from the command line. It prints the differences and sets a failing exit code, so a pipeline can stop on it.
On the real project the two lists agree. The output is one line.
npx tsx scripts/check-api-drift.tsNo drift: 6 operations are both served and documented.Now make two changes that an assistant could easily make on a busy day. It renames the free-slots folder to slots because that looks tidier. It also adds a convenient export route that nobody asked for, like the 'export all patients' endpoint in Error Handling and Backend Review. Try it on a copy, so that the real project stays clean.
cp -r . ../try-drift
cd ../try-drift
mv src/app/api/clinicians/\[clinicianId\]/free-slots src/app/api/clinicians/\[clinicianId\]/slots
mkdir src/app/api/export-patients
echo 'export const GET = () => Response.json({ patients: [] });' > src/app/api/export-patients/route.ts
npx tsx scripts/check-api-drift.tsServed but not documented: GET /api/clinicians/{clinicianId}/slots
Served but not documented: GET /api/export-patients
Documented but not served: GET /api/clinicians/{clinicianId}/free-slotsThe check found both changes. The rename shows up twice: the new URL is undocumented and the old one is no longer served. The export route has no contract entry, no requirement and no permission rule. The exit code is 1, so the pipeline would stop here. Run it twice and you get the same lines.
Keep decision records and diagrams true
A decision record says what was decided and why, on a certain date. It is history, like a page in a ledger. If you rewrite it later, a reader can no longer tell what the team believed at the time. So you never edit the decision. You change only the status line, and you write a new record.
- Accepted means in force today.
- A change of mind gets a new record that says which one it supersedes.
- The old record gets one change:
Status: Superseded by ADR-00x. Its date, context and reasons stay as they were. - A mistake of fact, such as a wrong date or a broken link, can be corrected in place and noted. A changed decision cannot.
The worked example is in Architecture Decision Records. If you also write a record with an assistant, the prompt Architecture Decision Record Draft helps, and the blog post Writing Architecture Decision Records (ADRs) with AI goes deeper.
Diagrams are different. A diagram describes the system as it is today, so it should be changed whenever the system changes. Because Tidewell's diagrams are written as Mermaid text, they live in the repository, and a change to them shows up in the same pull request as the code. When Module 6 added the email service, the context diagram gained a box in the same change. A reviewer can then see both at once. See Diagramming the Design for the diagrams and the Mermaid flowchart syntax (opens in a new tab) for the text format.
| If the change... | Then update... |
|---|---|
| Adds, renames or removes a route | openapi.yaml, the contract test, and the README if it names the route. |
| Adds a new outside service or a new part of the system | The context or component diagram, and a decision record if it was a real choice. |
| Reverses an earlier decision | A new record, and the old record's status line. Then the diagrams. |
| Adds or renames a command or a setting | README, operating notes, .env.example and the AGENTS.md file. |
| Changes a business rule | The acceptance criteria, after the owner of the rule confirms it. |
Make 'docs updated' part of the definition of done
People forget documents because the build still passes without them. The cure is to make a document part of what 'finished' means. In Module 3 you wrote a definition of done into AGENTS.md. Here is the same section, with the documentation lines added.
## Definition of done
- `npm run check`, `npm test` and `npm run docs:check` pass.
- The change traces to a requirement ID.
- New behaviour has a matching acceptance scenario in `docs/acceptance-criteria.md`.
- Docs are updated in the same change: README, operating notes, `docs/api/openapi.yaml`, diagrams and decision records, wherever the change touches them.
- An accepted decision record is never rewritten. Mark it superseded and add a new one.Part of the file: the definition of done. The docs:check script runs the drift check from this lesson.
What each part does
- The first line adds the drift check to the commands that must pass.
- The documents line makes the update part of the same change, not a promise for later.
- The last line tells assistants and people not to rewrite an accepted decision.
Then add two more habits. Put a line about documents into the pull request template, which the next lesson covers. And let the pipeline run npm run docs:check next to the tests, so a mismatch blocks the merge. The AGENTS.md (opens in a new tab) file is guidance, so the pipeline is the part that enforces it.
Step-by-step workflow: keep the documents true
Step 1: Name the source of truth for each document
Write down which file is right when two places disagree. For the API it is
openapi.yaml.What you should see: A table like the one near the start of this lesson.
Step 2: Add the drift check
Copy the script into
scripts/, add adocs:checkscript topackage.json, and run it.What you should see: It prints 'No drift' on a clean project.
Step 3: Put it in the pipeline
Add
npm run docs:checkas a step next to the tests, as in Module 7. Make it a required check.What you should see: A mismatch stops the merge.
Step 4: Decide when a difference appears
For each reported line, ask a person: is the code wrong or is the document old? If a route has no requirement, take it out of the code instead of documenting it.
What you should see: Each difference is fixed on the right side.
Step 5: Update diagrams and records in the same pull request
Use the table in this lesson. Change a decision's status instead of its text.
What you should see: The reviewer sees code, contract and diagrams together.
Step 6: Add the lines to the definition of done
Edit
AGENTS.mdand the pull request template so every change asks about documents.What you should see: Updating documents becomes a habit and not a favour.
- Change
Code or design
- Update docs
Same pull request
- Checks run
Contract and drift
- Difference?
A person decides
- Fix one side
Code or document
- Merge
Docs match code
The checks catch drift. A person decides which side is right.
What the assistant does and what you do
| Task | Assistant's part | Your part |
|---|---|---|
| Updating documents after a change | Can propose edits to the contract, diagrams and notes. | Check each edit against the code. Run the checks. |
| Comparing code and contract | Can list the differences you give it. | Decide which side is right. The check, not the assistant, is the proof. |
| Writing a new decision record | Can draft one from your notes. | Confirm the facts and the date. Mark the old one superseded yourself. |
| Redrawing a diagram | Can edit the Mermaid text. | Confirm that every box and arrow is real. |
| Choosing whether a new route is wanted | Not its job. | Check it against a requirement, a permission rule and the owner. |
Conclusion and your next step
Documents stay true when each one has a source of truth, a check and an owner. The OpenAPI file leads, and a drift check compares it with the real routes. Decision records change status and keep their history. Diagrams move with the code. And 'docs updated' is part of the definition of done.
Your next step: the next lesson is about honesty. Learn how to record where an assistant helped and what a person really checked in Recording AI Assistance and Review.
For more on contracts, read Designing an API Contract again with the drift check in mind, and try the prompt REST API Design Review.
Reusable prompt
Compare the contract with the code
Asks an assistant to explain each difference between the API contract and the routes, without editing either one.
You are helping me review documentation drift. Do not edit the contract or the code. Do not guess business rules.
Project: tidewell-booking, a fictional clinic booking system.
The drift check printed:
Served but not documented: GET /api/clinicians/{clinicianId}/slots
Served but not documented: GET /api/export-patients
Documented but not served: GET /api/clinicians/{clinicianId}/free-slots
Requirements: FR-01 a patient can see free slots for a chosen clinician and date. There is no requirement for exporting patients. Personal data is protected under CON-01.
Tasks:
1. For each line, say which case it most likely is: the document is old, the code deviates from the contract, or a person must decide.
2. For each, say which role should decide (developer, practice manager or clinic owner) and why.
3. For each, suggest the smallest safe fix, but do not apply it.
4. List what this check cannot tell us, such as response fields or permissions.Show the reusable template
Replace each {{placeholder}} with your own details.
You are helping me review documentation drift. Do not edit the contract or the code. Do not guess business rules.
Project: {{project_and_scope}}.
The drift check printed:
{{drift_output}}
Requirements: {{relevant_requirements_and_constraints}}
Tasks:
1. For each line, say which case it most likely is: the document is old, the code deviates from the contract, or a person must decide.
2. For each, say which role should decide ({{roles}}) and why.
3. For each, suggest the smallest safe fix, but do not apply it.
4. List what this check cannot tell us, such as response fields or permissions.Expected output and limitations
A short list with one entry per drift line, giving the likely case, the deciding role and the smallest safe fix, then a list of what the check cannot show.
1. Served: GET .../slots; documented: GET .../free-slots.
Likely: the code deviates from the contract (a rename). Decide: developer.
Smallest fix: rename the folder back to free-slots. If the new name is wanted, change the contract and tell any client first.
2. Served: GET /api/export-patients. No requirement.
Likely: unrequested route that exposes personal data. Decide: clinic owner (CON-01) and developer.
Smallest fix: remove the route. Do not document it.
Not covered by this check: response fields, status codes, permissions and who may call each route.Limitations to keep in mind
- The assistant is guessing the cause from three lines. Look at the pull request history to confirm.
- It may suggest updating the contract to match the code. Treat that as a question for a person, not a fix.
- It cannot see the code or the contract unless you paste them, so its list of what the check misses is general.
Common errors and how to fix them
The contract is updated by hand after the code, so it only ever describes the past.
Why it happens: There was no check, and updating the document was optional.
Fix: Run a contract test and a drift check in the pipeline, and make them required checks.
An old decision record is rewritten to match what the team does now.
Why it happens: Editing felt tidier than adding a new record.
Fix: Restore the original text from history. Mark the record superseded, and write a new one that says what changed and why.
The assistant 'fixes' a drift report by documenting a route that nobody asked for.
Why it happens: It made the two sides match without asking whether the route should exist.
Fix: Check every undocumented route against a requirement, a permission rule and its owner before it is allowed to stay.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
A drift report for Ferngate Cycle Repairs
Ferngate's parts tracker has drifted. Write the drift report that the check would print, then say for each line whether the code or the document should change, and which role decides.
You will need
- Routes the code serves: GET /api/parts, POST /api/jobs/{jobId}/parts-used, GET /api/parts/export.
- Paths in openapi.yaml: GET /api/parts, POST /api/jobs/{jobId}/parts, GET /api/low-stock.
- Requirements: a mechanic can record a part taken for a job; the owner is warned about low stock. The low-stock threshold is 'to be agreed'.
- Roles: developer and workshop owner.
Acceptance criteria
Your work is done when every one of these is true.
Hints (2)
- Compare the two lists in both directions, as the script does.
- Ask whether any requirement needs the export route before you decide what to do with it.
Show a model answer
A strong answer prints four lines: parts-used and export as served but not documented, and parts and low-stock as documented but not served. It treats parts-used against parts as one rename and asks the developer which name the contract promised, preferring to keep the contract's name. It questions the export route, which no requirement asks for, and leans towards removing it unless the workshop owner wants it. It notes that the low-stock route may be planned but not built, and that its threshold is still to be agreed. It also says the check ignores response fields and permissions.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. The route might be wanted and undocumented, or it might be an unwanted extra. Adding it to the contract is tempting because the check then passes, but it can hide a route that exposes data nobody approved. Turning the check off removes the protection.
Show the answer and explanation
Answer: C. The old record is history and shows what the team knew then. Rewriting is tempting because it looks tidy, but it destroys that history. Deleting it has the same effect.
Show the answer and explanation
Answer: A. Documents are easy to skip because nothing breaks at once. Making them part of done turns the update into a step. They do not affect speed, and no tool knows the reasons behind your changes.
Frequently asked questions
How do I keep API documentation up to date?
Make one file the source of truth, such as an OpenAPI file, and check it automatically. Run a contract test and a drift check in your pipeline, and update the file in the same pull request as the code. A failing check then stops a mismatch from merging.
What is a drift check?
It is a small script that compares two lists and prints the differences. Here it compares the routes the code serves with the paths in the OpenAPI file. It catches a renamed route or an extra one that nobody documented.
Should I edit an old architecture decision record?
Not to change the decision. If the decision changes, write a new record and set the old one's status to Superseded. You may fix a plain mistake of fact, such as a wrong link, and note that you did.
Who should update the documentation when the code changes?
The person who makes the change, in the same pull request. The reviewer checks that the documents match. The owner of a business rule confirms any change to the rule itself.
- 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 v3.2.1(opens in a new tab)
OpenAPI Initiative · Official documentation · The format of the contract. The page shows the current version, which can change.
- Architectural Decision Records (ADRs)(opens in a new tab)
ADR GitHub organisation · Background on decision records and their status values.
- Route Handlers(opens in a new tab)
Next.js · Official documentation · How route files map to URLs. This convention is specific to Next.js.
- Keep a Changelog(opens in a new tab)
Keep a Changelog · A simple way to tell users what changed in each release.
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.