API Documentation and Developer Experience Questions
Documentation and developer experience for API consumers: reference docs for endpoints and fields, OpenAPI-driven and interactive documentation, quickstarts and runnable code samples, doc comments that feed generated reference, changelogs, deprecation notices and migration guides, error messages and error tables that explain themselves, developer portals, sandboxes and onboarding flows. Covers developer experience (DX) as a product concern: time to first successful call, DX and docs-effectiveness metrics and dashboards, diagnosing onboarding drop-off, developer feedback loops, experiments and developer research, documentation standards and CI checks across teams, prioritising DX investment, and reducing support load through better docs and self-service. Designing the API itself (versioning policy, auth, rate limits, webhooks, gateways, SDK engineering) is a separate subject.
With limited engineering capacity, how do you weigh investing in developer experience for internal teams against external third-party developers? What evidence would you use to decide?
Sample Answer
Direct answer
I would not split the effort evenly by default. I would invest first where the measured pain and the business value are largest, and in the meantime build the shared foundation (an accurate API description, working docs, a consistent error format) that helps both audiences. For most companies with limited capacity, that means a small, cheap fix list for internal teams (because their pain is large and quick to measure) and a focused investment in external onboarding only if external adoption is what drives revenue. The deciding evidence is numbers, not opinion.
Developer experience (DX) here means how easy and pleasant it is to discover, understand, try and correctly use an API. Two more terms: a funnel is the ordered steps a developer passes through (signup, then first successful call, then real use), and time to first call is the time from signup to that first successful request.
The two audiences want different things
| Internal teams | External third-party developers | |
|---|---|---|
| Typical high-value features | Single sign-on (SSO, one company login for every tool) and easy access requests, telemetry (usage and error data) on their own calls, shared client libraries (one maintained code package for calling a service, so teams do not each write their own), a service catalogue (an internal directory listing every service, its owner and its docs) | Self-serve signup and keys, a quickstart that ends in a working call, a sandbox (a safe test copy of the API), clear docs, stable versioning and a changelog (a dated list of changes) |
| What they tolerate | Rough edges, because they can ask a colleague on chat | Almost none, because they can simply leave |
| Cost of a bad experience | Lost engineer hours, slower features | Lost signups, lost revenue, support load |
| Who fixes a problem | You can mandate a change | You can only influence, and you must not break them |
Evidence I would collect
- For internal: hours spent waiting for access or debugging (survey plus ticket counts), time for a new team to make its first call to a service, number of teams reimplementing the same client.
- For external: the funnel from signup to first successful call, the share of developers who reach it, support tickets per integration, integrations blocked in "in progress" for more than a month, revenue tied to API partners.
- Strategic context: is the API the product (external wins) or a way to build the product faster (internal wins)? Are there contracts at risk?
Worked example (illustrative numbers)
Internal: 60 engineers each lose about 2 hours a week to access requests and missing telemetry, so 60 x 2 = 120 hours a week, roughly 3 engineer-weeks of 40 hours every week. A two-week fix (SSO-based access plus a shared dashboard) that removes most of it pays back within a few weeks.
External: 300 developers sign up a month and 20 percent reach a first call, so 60 do. A better quickstart and sandbox lifts that to 35 percent, so 105, or 45 more integrating developers a month.
Put both on one basis, money per month. Internal: 120 hours a week is about 520 hours a month (120 x 4.33); at an assumed 80 per hour fully loaded cost, that is about 41,600 a month. The two-week fix costs 2 engineers x 2 weeks x 40 hours x 80 = 12,800 once (160 hours at 80), so it pays back in roughly 0.3 months (12,800 / 41,600, about 9 days) if it removes all of the loss; at half effectiveness (saving 20,800 a month) it pays back in about 0.6 months, or 2.5 to 3 weeks. External: assume one integration is worth 500 a month in revenue (an assumed figure to replace with your own). 45 more integrations is 22,500 a month, and it keeps compounding as each developer stays. If the external fix costs, say, 4 engineer-weeks (12,800), payback is about 0.6 months. Here internal pays back faster if the fix works well (0.3 months against 0.6), and roughly ties external if it works only half as well, while external accumulates longer. I would do the internal fix first because its loss is measured and near-certain, then external. If your real revenue per integration were 2,000, external would clearly win.
If both returns are close, choose the one that is cheaper to reverse (easier to undo if it turns out wrong).
What would change my call
- If the API is the company's revenue product, or a launch depends on partners, external goes first.
- If a platform team supports many internal teams and adoption of an internal API is lagging, internal goes first.
- If external developers cannot yet succeed at all (no docs, no keys), fix that floor before polishing anything internal.
Pitfalls
- Treating internal DX as free. Internal developers are expensive, and their friction is invisible unless measured.
- Building two systems. Use one spec, one docs site with an internal-only section, one error format.
- Measuring activity, not outcomes. Pages published tell you nothing; time to first call does.
Tell me about a time you improved the onboarding experience for developers using an API or platform. What was the problem, what did you change, and what moved as a result?
Sample Answer
Direct answer
A strong answer tells one specific story: a measured onboarding problem, a change I personally led that addressed its actual cause, and a result with numbers I can explain. Below is a story skeleton in STAR order (Situation, Task, Action, Result: the standard behavioural structure). Numbers are illustrative; in the room, use your real ones and say how you measured them.
Situation
I owned developer experience for a payments-style API. (If you have no API story, use any developer-facing tool you supported, or an internal platform: the shape is the same, a measured drop-off, a diagnosed cause, one change, a comparison.) New developers had to create an account, wait for a sales review to get keys, then read a large reference to work out what to call first. Support and a product survey showed that many signups never made a call. When I sampled signups, about 22 of every 100 reached a first successful call (an HTTP response with a 2xx status code, the family of codes meaning success) within a week. (Illustrative.)
Task
I was asked to raise that share, without weakening the review that protected us from misuse. My goal was to make the first successful call quick and self-serve, and to measure success as the share of signups reaching a first successful 2xx response within 7 days, plus the median time to it.
Action (the specific things I did)
- Found the real cause before changing anything. I watched five new developers attempt the flow, and grouped failing requests in the server logs. Two problems dominated: they could not get a key without waiting, and the quickstart's first request used the wrong header format (a header is a named line sent with each request, such as
Authorization), and the server answered 401 (the status code for "missing or invalid credentials") with no hint of what was wrong. - Split keys into a sandbox and a production tier. A sandbox is a safe test copy of the API; its keys were instant and worked on fake data. The review remained, but only for production keys.
- Rewrote the quickstart as one runnable page with the key pre-filled after login, tested it myself on a fresh machine and had an engineer outside the team run it.
- Improved the 401 error message to name the header and link to the docs.
- Instrumented the funnel (counted how many people reached each step: signup, key, first call) so cohorts could be compared, and ran the rollout as a fair test: each new account was randomly assigned by a coin flip at signup to the old or the new flow, over the same two weeks, so both groups (cohorts) saw the same marketing and season.
Result
With 200 signups in each cohort, the share reaching a first successful call within 7 days moved from 44 of 200 (22%) with the old flow to 78 of 200 (39%) with the new one. Support tickets tagged "cannot get started" also fell, and the sales team reported that reviews for production keys were now from developers who had already built something. What I would say I learned: the biggest gain came from removing the wait, not from writing more documentation. (Numbers illustrative.)
Why this answer works, and pitfalls
- It names a measurable outcome, the change tied to the diagnosed cause, and a fair comparison (two cohorts), so the result is believable.
- Be ready to own what did not work: for example, an early version of the sandbox behaved differently from production and I had to fix parity.
- Avoid stories where you "wrote better docs" with no diagnosis and no metric, and avoid claiming credit for team outcomes: say what you personally did.
- If you have no numbers, say so and give the directional evidence (ticket themes, funnel shape) rather than inventing figures.
Write the code samples for a quickstart that make an authenticated GET to a users endpoint in three languages, parse the list response, and handle an authorization failure. What makes a sample good for a copy-paste reader, and how would you stop these samples going stale?
Sample Answer
Direct answer
A good quickstart sample is a complete, minimal program that a stranger can paste, set one environment variable for, and run unchanged. It makes the authenticated request, reads the list out of the response, and handles the one failure every newcomer hits first (a rejected key) with a message that says what to do. To stop samples going stale, they must live as real files that CI (continuous integration, the automated build run on every change) executes against a sandbox, and the docs page must include them from those files instead of holding pasted copies. A contract test compares real API responses to the OpenAPI description.
Approach
Core to the answer: the three samples and the reasons they are good. Optional: the local stand-in server, which only proves the samples run.
The endpoint returns a JSON body shaped like {"data": [ {"id": ..., "email": ...} ], "next_cursor": null}. OpenAPI is the standard machine-readable description of an API. A sandbox is a safe test copy of the API with fake data. The API key travels as a bearer token (a credential sent in the Authorization header). Status 401 means the credentials are missing or invalid, 403 means the key is valid but not allowed to do this; both get the same friendly handling in a first sample. The base URL is read from an environment variable with a production default, so the identical code can be run against a test server.
Sample 1: curl (shell, needs jq, a command-line JSON reader)
#!/usr/bin/env bash
# Needs: curl, jq. Set API_KEY first. BASE_URL defaults to the production API.
# ${BASE_URL:-default} means: use BASE_URL if set, otherwise the default after ':-'.
BASE_URL="${BASE_URL:-https://api.example.com/v1}"
status=$(curl -sS -o response.json -w '%{http_code}' \
-H "Authorization: Bearer $API_KEY" \
"$BASE_URL/users?limit=2")
if [ "$status" = "401" ] || [ "$status" = "403" ]; then
echo "Authorization failed (HTTP $status). Check that API_KEY is set and current." >&2
jq -r '.error.message' response.json >&2
exit 1
fi
jq -r '.data[] | "\(.id) \(.email)"' response.json
What the curl flags do: -sS hides the progress meter but still prints errors; -o response.json saves the body to a file; -w '%{http_code}' prints just the status code, which the script captures in status; -H adds a header.
Sample 2: Python (with the requests library, saved as quick.py)
import os
import sys
import requests
BASE_URL = os.environ.get("BASE_URL", "https://api.example.com/v1")
API_KEY = os.environ.get("API_KEY", "")
resp = requests.get(
f"{BASE_URL}/users",
params={"limit": 2},
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=10, # seconds to wait before giving up
)
if resp.status_code in (401, 403):
print(f"Authorization failed (HTTP {resp.status_code}). Check that API_KEY is set and current.",
file=sys.stderr)
print(resp.json()["error"]["message"], file=sys.stderr)
sys.exit(1)
resp.raise_for_status()
for user in resp.json()["data"]:
print(user["id"], user["email"])
Sample 3: JavaScript (Node 18 or later, built-in fetch, saved as quick.mjs)
const BASE_URL = process.env.BASE_URL ?? "https://api.example.com/v1";
const API_KEY = process.env.API_KEY ?? "";
const resp = await fetch(`${BASE_URL}/users?limit=2`, {
headers: { Authorization: `Bearer ${API_KEY}` },
signal: AbortSignal.timeout(10_000),
});
if (resp.status === 401 || resp.status === 403) {
const body = await resp.json();
console.error(`Authorization failed (HTTP ${resp.status}). Check that API_KEY is set and current.`);
console.error(body.error.message);
process.exit(1);
}
if (!resp.ok) throw new Error(`Unexpected HTTP ${resp.status}`);
const { data } = await resp.json();
for (const user of data) console.log(user.id, user.email);
Proving they run: a local stand-in server (save as mock_api.py)
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
USERS = [{"id": "usr_1", "email": "ada@example.com"},
{"id": "usr_2", "email": "grace@example.com"}]
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
ok = self.headers.get("Authorization") == "Bearer test_key_123"
code, body = (200, {"data": USERS, "next_cursor": None}) if ok else (
401, {"error": {"code": "invalid_api_key", "message": "API key is missing or invalid."}})
payload = json.dumps(body).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def log_message(self, *args):
pass
HTTPServer(("127.0.0.1", 8765), Handler).serve_forever()
Run it and the Python sample, once with a good key and once with a bad one:
python3 mock_api.py &
export BASE_URL=http://127.0.0.1:8765/v1
API_KEY=test_key_123 python3 quick.py
API_KEY=wrong python3 quick.py; echo "exit code: $?"
Output:
usr_1 ada@example.com
usr_2 grace@example.com
Authorization failed (HTTP 401). Check that API_KEY is set and current.
API key is missing or invalid.
exit code: 1
The curl and Node versions print the same lines against the same server.
What makes a sample good for a copy-paste reader
- Runs unchanged: the only setup is
API_KEY. No placeholders inside the code that must be edited. - Key from the environment, never inline: a pasted key ends up in screenshots, shell history and git.
- Shows the response shape being used: the loop reads
data, so the reader learns the list lives under that field. - Fails helpfully: prints the cause and a next step, exits non-zero (a non-zero exit code is how a program tells scripts it failed) so scripts notice; error messages go to stderr (the error output stream, separate from normal output).
- Has a timeout: without one, a stuck network hangs the newcomer's terminal with no explanation.
- Same behaviour in all three languages, so switching language never changes the story.
Keeping samples from going stale
- Store each sample as a file in the repository and include it into the docs page at build time (docs-as-code: docs built from source files by the same build process as software).
- CI runs every sample against the sandbox on each pull request (a proposed code change awaiting review) and nightly (once a night on a schedule). A non-zero exit fails the build, which is why the samples exit properly.
- A contract test compares real API responses to the OpenAPI description, so a renamed field breaks the build before it breaks a reader.
- Pin the language versions the docs claim (for example "Node 18 or later") and test the oldest one.
- Name an owner: the team that changes the endpoint fixes the samples in the same pull request.
Complexity and edge cases
Each sample makes one request and one pass over the returned page: O(n) time and memory (work and storage grow in proportion to n, the number of users in the page), with n capped by limit. Edge cases a quickstart should acknowledge, even if it does not solve them all: an empty data list (loop prints nothing, so add a line saying so in the guide), next_cursor not null (a later guide shows how to page on), a 429 rate-limit response (wait and retry), a non-JSON error body from a proxy (an intermediate server returning its own plain-text error page instead of the API's JSON; the Python and Node samples would raise here, acceptable in a quickstart but named in the troubleshooting page), and a missing API_KEY (sent as an empty token, which produces the same 401 message).
Trade-offs
Three languages triple the maintenance, which is exactly why the CI run matters. Generated samples from the OpenAPI description are cheap but read as generic; hand-written quickstarts teach better, generated ones cover the long tail of endpoints.
You are deprecating a widely used list-users endpoint in favor of a redesigned v2 endpoint whose response shape differs. Write the changelog entry and the short migration note clients will read, and explain what makes them usable by someone who skims.
Sample Answer
Direct answer
Write a changelog entry that states what changes, who is affected and the two dates (deprecation and shutdown), then a migration note that is a short before-and-after with a field mapping table and a "what to do by when" list. It is usable by a skimmer when the first line says whether they must act, the dates are exact, the change is shown as code, not described, and the detail is layered underneath.
Terms: a cursor is an opaque bookmark string the server returns with a page of results; you send it back to get the next page, instead of asking for "page 2". That is why a total count disappears: the server no longer numbers pages, it only knows where you left off. A changelog is a dated public log of changes to the API. Deprecating an endpoint means announcing it will be retired while it still works. Sunset is the date it stops working.
The changelog entry
2026-10-01 DEPRECATION GET /v1/users will be removed on 2027-04-01
Action required if you call GET /v1/users. Use GET /v2/users instead.
Nothing changes for other endpoints.
- Deprecated: 2026-10-01. Still works, and now returns Deprecation and Sunset headers.
- Removed: 2027-04-01. After this date /v1/users returns 410 Gone.
- Why: v2 adds cursor pagination and fixes inconsistent field names.
- Migration guide: /docs/migrate-list-users
The migration note
Who is affected: anyone calling GET /v1/users. Check your logs for that path.
What to change, in three steps:
- Change the URL from
/v1/usersto/v2/users. - Replace page numbers with the cursor (
?limit=50&cursor=...). - Read the list from
datainstead of the top level.
Paging loop under v2 (Python):
import requests
cursor = None
users = []
while True:
params = {"limit": 50}
if cursor:
params["cursor"] = cursor
body = requests.get("https://api.example.com/v2/users", params=params,
headers={"Authorization": "Bearer KEY"}).json()
users.extend(body["data"])
cursor = body.get("next_cursor")
if not cursor:
break
Call 1 sends no cursor and returns 50 users plus next_cursor: "abc123"; call 2 sends cursor=abc123 and returns the next 50; the last page has no next_cursor, so the loop stops.
Before (v1):
{"users": [{"id": 7, "name": "Ana"}], "page": 1, "total": 240}
After (v2):
{"data": [{"id": "usr_7", "full_name": "Ana"}], "next_cursor": "abc123"}
| v1 | v2 | Note |
|---|---|---|
users | data | Renamed |
id (number) | id (string, usr_ prefix) | Type changed. Store as text. |
name | full_name | Renamed |
page, total | next_cursor | Loop until it is absent. Total is no longer returned. |
Signals in the API itself. Headers are name-value lines sent with every response, so a program can read them without parsing prose. Starting on the deprecation date, v1 responses carry Deprecation: @1790812800 (the date 2026-10-01 as a Unix timestamp, the format RFC 9745 defines) and Sunset: Thu, 01 Apr 2027 00:00:00 GMT (RFC 8594). Programs can detect them, so warnings show up in client logs without anyone reading the changelog.
What makes it skimmable
- Lead with the action, then the reasons.
- Exact dates, not "soon" or "next quarter". 182 days separate the deprecation and removal here.
- Code and a table, not paragraphs. A reader can copy the new call.
- One task per step, in order, and each step is checkable.
- Say what does NOT change, so most readers can stop reading.
- Specific error after the sunset (410 Gone), the HTTP status meaning "this resource existed and was removed on purpose", so nobody is guessing.
Pitfalls
- Changing the type of
idis the sneakiest break; call it out. - Do not remove a field without a mapping row. Do not bury the dates in the last paragraph.
- Give the migration a support channel, and send the notice by email to key owners found in usage logs, since many will never read a changelog.
Produce the OpenAPI 3.0 description for a create-payment endpoint in a payments API, written so the generated reference page needs no extra explanation: request body, responses including the failure cases a developer will hit, and realistic example values.
Sample Answer
Direct answer
Write the OpenAPI description so every fact a developer needs is in the contract itself: what to send, with realistic values, and what each failure means and how to react. OpenAPI (the standard, machine-readable format for describing an HTTP API, usable by reference-page generators and generators that produce an SDK, the language-specific client library) turns that contract into the reference page. Below is a complete OpenAPI 3.0 description of POST /payments.
How to read the YAML
Read it top to bottom in this order:
pathslists each URL and HTTP method;operationIdis the unique name generators turn into an SDK method (createPayment).security: - bearerAuth: []says the call needs the auth scheme namedbearerAuth. That name is defined at the bottom insecuritySchemes: a bearer token is a secret string sent asAuthorization: Bearer <token>.componentsis a shelf of reusable pieces.$ref: '#/components/schemas/Payment'means "use the definition stored at that path in this same file", so the same error shape is written once and pointed at many times. A shape written directly in place instead of via$refis "inline".enumis a closed list of allowed values (statuscan only bepending,succeededorfailed);format: date-timemarks a string as an ISO 8601 timestamp such as2026-09-28T10:15:30Z.- Status codes used: 201 created, 400 invalid request, 401 not authenticated, 402 payment required (used here for a declined payment method), 409 conflict with something in progress, 422 well-formed but rejected, 429 rate limited.
Idempotency-Keyis a header carrying a unique string per logical payment; if the client retries after a timeout, the server sees the same key and does not charge twice.Retry-Afteris a response header telling the client how many seconds to wait. ISO 4217 is the standard list of three-letter currency codes (USD, EUR).
The description
openapi: 3.0.3
info:
title: Payments API
version: "2026-09-01"
servers:
- url: https://api.example.com/v1
paths:
/payments:
post:
operationId: createPayment
summary: Create a payment
description: >
Charges a saved payment method. Send an Idempotency-Key header so a
retry after a timeout cannot charge the customer twice.
security:
- bearerAuth: []
parameters:
- name: Idempotency-Key
in: header
required: true
description: Unique string (for example a UUID) per logical payment. Reusing it with a different body returns 422.
schema:
type: string
maxLength: 64
example: 7c1d2f0e-5b3a-4a52-9c67-0d2a1e8f4b11
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreatePaymentRequest'
examples:
card_payment:
summary: 25.00 USD on a saved card
value:
amount: 2500
currency: USD
payment_method_id: pm_1042
description: Order 8841
responses:
"201":
description: Payment created (status may still be pending).
content:
application/json:
schema:
$ref: '#/components/schemas/Payment'
example:
id: pay_9137
amount: 2500
currency: USD
status: pending
created_at: "2026-09-28T10:15:30Z"
"400":
$ref: '#/components/responses/ValidationError'
"401":
$ref: '#/components/responses/Unauthorized'
"402":
description: Payment method declined. The decline_code field says why.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
example:
type: https://docs.example.com/errors/card-declined
title: Card declined
status: 402
detail: The issuing bank declined this card. Ask the customer for another payment method.
decline_code: insufficient_funds
"409":
description: Another request with the same Idempotency-Key is still in progress. Retry after a short delay.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
"422":
description: Idempotency-Key was reused with a different request body.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
"429":
description: Rate limit exceeded. Wait for the number of seconds in Retry-After.
headers:
Retry-After:
schema:
type: integer
description: Seconds to wait before retrying.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
schemas:
CreatePaymentRequest:
type: object
required: [amount, currency, payment_method_id]
properties:
amount:
type: integer
minimum: 1
description: Amount in the smallest currency unit (2500 means 25.00 USD).
example: 2500
currency:
type: string
pattern: '^[A-Z]{3}$'
description: Three-letter ISO 4217 code.
example: USD
payment_method_id:
type: string
example: pm_1042
description:
type: string
maxLength: 200
example: Order 8841
Payment:
type: object
required: [id, amount, currency, status, created_at]
properties:
id: {type: string, example: pay_9137}
amount: {type: integer, example: 2500}
currency: {type: string, example: USD}
status:
type: string
enum: [pending, succeeded, failed]
created_at: {type: string, format: date-time}
Problem:
type: object
required: [type, title, status]
properties:
type: {type: string, format: uri}
title: {type: string}
status: {type: integer}
detail: {type: string}
decline_code:
type: string
description: Only on 402. Machine-readable decline reason.
errors:
type: array
items:
type: object
properties:
field: {type: string}
message: {type: string}
responses:
ValidationError:
description: A field failed validation. The errors array names each field.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
example:
type: https://docs.example.com/errors/validation
title: Invalid request
status: 400
errors:
- field: currency
message: must be a three-letter uppercase ISO 4217 code
Unauthorized:
description: Missing, expired or invalid bearer token.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
Choices in it
- Amounts as integers in the smallest currency unit, stated in the field description with the example
2500 means 25.00 USD. This prevents the most common payment bug (floating point). - Idempotency-Key is required, and its failure cases (409 in progress, 422 different body) are documented because they are exactly what a retrying developer will hit. An idempotency key lets a retried request be recognised as the same payment.
- Failure responses are first-class: 400 (which field), 401, 402 (declined, with a machine-readable
decline_code), 429 (withRetry-After). Errors use the RFC 9457 problem-details shape (a standard JSON error format, sent with the media typeapplication/problem+json). - Examples on the request, on the 201, and on the error bodies, with realistic values, so the rendered page needs no prose around it.
- Shared pieces in
components($ref) so error shapes are defined once. - OpenAPI 3.0 specifics (a detail rarely asked about in interviews):
exampleon schemas andexampleson media types; 3.1 later aligned schemas with JSON Schema, which changes some of these keywords. The structure above is the same in both.
Check that it is valid and consistent
Save the spec as payments.yaml and run the script below. In plain words: it loads the YAML into nested dictionaries; resolve takes a pointer like #/components/schemas/Payment, drops the leading #/, and follows each name in turn through the dictionaries (a wrong path raises a KeyError); walk visits every part of the spec and resolves every $ref it finds; finally it checks that the request example contains every field listed as required.
import yaml
spec = yaml.safe_load(open("payments.yaml"))
def resolve(ref):
node = spec
for part in ref[2:].split("/"):
node = node[part]
return node
def walk(node):
if isinstance(node, dict):
if "$ref" in node:
resolve(node["$ref"])
for value in node.values():
walk(value)
elif isinstance(node, list):
for value in node:
walk(value)
walk(spec)
op = spec["paths"]["/payments"]["post"]
print("openapi", spec["openapi"], "- all $refs resolve")
print("responses:", ", ".join(op["responses"]))
example = op["requestBody"]["content"]["application/json"]["examples"]["card_payment"]["value"]
required = spec["components"]["schemas"]["CreatePaymentRequest"]["required"]
print("example has every required field:", all(k in example for k in required))
Output:
openapi 3.0.3 - all $refs resolve
responses: 201, 400, 401, 402, 409, 422, 429
example has every required field: True
This is a structural check, not a full OpenAPI validation; in a real project also run a linter such as Spectral (a rule checker for OpenAPI files, for example one that fails when an operation has no description).
Where it lives and how examples stay current
Keep the file in the API's own repository, reviewed in the same pull request as the code, and publish the reference page from it in CI (continuous integration, the automated build run on every change). The same rule holds for any API, public or internal: the spec sits with the service and the doc site builds from it. Keep examples honest by running contract tests (automated tests that check the running service's real responses against the spec; tools such as Schemathesis generate test requests from the spec), and fail the build on drift (the spec and the real behaviour quietly disagreeing).
Referencing it from other documents
If another document needs to mention this endpoint, do not paste the spec. Link to it and summarise what that reader needs: authentication (bearer tokens), the versioning pattern (major version in the path, /v1, with only additive changes inside a version), rate-limit behaviour (429 plus Retry-After), and the idempotency rule.
Pitfalls
Only documenting the 200 path, examples like "string", and a spec hand-edited apart from the code all produce a reference page that looks complete and misleads.
Unlock Full Question Bank
Get access to all 34 API Documentation and Developer Experience interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.