00.8 Reading API Documentation
Every service you will ever integrate — a payments provider, a map API, an LLM provider, a vector database, a workflow tool — comes with a pile of documentation, and almost nobody reads it cover to cover. The skill that separates engineers who ship in an afternoon from engineers who stall for a week is knowing which page to open, what each part of it is for, and how to check that what it says is still true. This lesson teaches you to read API documentation the way a professional does: map the docs site first, learn the anatomy of a reference page, use the machine-readable versions when they exist, read SDK docs as a layer over the REST docs, verify volatile facts against live sources, and treat error messages as part of the documentation.
What you'll learn
- The anatomy of an API documentation site: quickstarts, guides, the API reference, SDK docs, changelogs, deprecation and migration guides, status pages, rate-limit and pricing pages — and which to read first for a new service
- How to read a single reference entry: endpoint, parameters (path, query, header, body), request and response examples, error codes, pagination and beta markers — with a worked reading of one real endpoint on each of OpenAI, Anthropic, Gemini and OpenRouter
- How to spot what the docs don't say, and why that matters
- How to read a rate-limit or pricing page: the unit (RPM versus TPM), scope, tier, measurement, signals and caps to extract before you write a loop
- OpenAPI: what the specification is, how to read
paths,components/schemas,serversandsecuritySchemes, which of the big providers publish one (verified as of November 2026), and what Swagger UI and Redoc do with it llms.txtand other machine-readable docs, and the new wave of docs MCP servers that let an assistant search documentation for you — with the verification routine that keeps that safe- How SDK documentation maps onto the REST documentation underneath it, and how to use
help(), type hints, PyPI pages, READMEs, CHANGELOGs and library source code as documentation - How to verify what the docs claim: docs-versus-reality checks, source-reliability rules, volatile facts (model names, prices, limits), and keeping a dated notes file of facts you have confirmed
- How to read API errors and Python tracebacks as documentation: error bodies,
request-idheaders, errortype/codefields, and where each provider documents its errors - How to use an AI assistant to read docs faster — and the verification routine that stops it from confidently inventing API parameters
- A complete worked exercise: integrating a brand-new, fictional shipping API from its documentation alone, including writing and running a standard-library Python client against a fake server
What you don't need
- API keys or accounts. Everything runnable in this lesson uses the Python standard library against a fake server on your own machine. The real provider pages are read, not called.
- Deep HTTP knowledge — lesson 00.6 covers methods, status codes, headers and JSON, and this lesson builds directly on it.
- Python beyond what Module 01A teaches; every snippet here is explained as it appears.
Setup
You need a terminal and a text editor (lesson 00.1 sets both up) and Python 3.11 or newer — check with python3 --version. No API key needed. The only code you run is standard-library Python:
python3 --version # need 3.11 or newerThe worked exercise in Part 8 uses a few small files you create yourself — a fake API server, a client, a demo driver and an OpenAPI document — all printed in full in that part. Everything else in the lesson is reading, tables and small snippets you can paste into any Python 3.11+ interpreter.
What you must be able to do after this lesson#
- Name the parts of an API documentation site and which to read first
- Read one reference entry and pull out its endpoint, parameters and errors
- Extract the unit, scope and limits from a rate-limit page
- Read the basics of an OpenAPI spec
- Verify a claim in the docs by testing it
- Integrate an unfamiliar API using only its docs
Why this matters for an AI engineer#
You will read more API documentation in this path than almost any other kind of text, because every provider you use is a documented HTTP API:
| You'll hear... | You'll understand it after... |
|---|---|
"Check the docs — the parameter is called max_completion_tokens, not max_tokens." |
2.1 The anatomy of a reference entry |
| "That endpoint is still in beta — the docs page has a warning banner." | 2.6 What the docs don't say |
| "The changelog says that field was renamed in the last SDK release." | 4.4 Versions, changelogs and deprecation warnings |
| "The docs page is wrong — the API rejects that parameter." | 5.1 Docs versus reality |
| "Look it up in the OpenAPI spec, not the HTML page." | Part 3: Machine-readable documentation |
| "Ask the docs MCP server instead of guessing." | 3.6 Docs MCP servers and doc-search tools |
| "That model name and price are from last month — check the pricing page." | 5.3 Volatile facts: model names, prices and limits |
"The 429 response has a Retry-After header and a request-id." |
Part 6: Errors as documentation |
| "The chatbot gave me a parameter that doesn't exist." | Part 7: AI assistants for reading docs |
| "We need to integrate this new vendor — nobody has used it before." | Part 8: Worked exercise |
Part 1: The anatomy of API documentation#
1.1 A docs site is a map, not a book#
Open any serious API's documentation and you will find the same neighbourhoods, arranged differently by each vendor. Learn the map once and every new service becomes faster to navigate.
| Section | What it contains | When you need it |
|---|---|---|
| Overview / landing page | What the service does, the big ideas, links everywhere | First contact with a service; orientation in 2 minutes |
| Quickstart | The shortest path to a first successful call | Day one: prove auth and connectivity before anything else |
| Authentication | How to get a key, which header or query parameter carries it, scopes, rotation | Before your first real request; again when keys leak or rotate |
| Concepts / guides | The mental model: resources, objects, lifecycles, pricing mechanics, rate-limit philosophy | When the reference page alone doesn't explain why |
| API reference | Every endpoint, every parameter, every response field, every error — exhaustively | The page you live in once you know what you want |
| SDK docs | The same API through the official client library: method names, types, helpers | When you use the SDK (almost always) |
| Tutorials / cookbooks | Worked examples for common tasks | When you want a pattern copied and adapted |
| Changelog / release notes | What changed, when, and what replaced it | Before upgrading a dependency; when behaviour suddenly differs |
| Deprecations / migration guides | What is being removed, when, and how to move | The moment you see a warning, or a model/endpoint "will be retired" |
| Status page | Is the service up right now, and what incidents are open | When calls fail and you suspect them, not you |
| Rate limits / pricing | How much you can call, what it costs, tiers and quotas | Before shipping anything that loops or bills |
| Community / support | Forums, Discord, GitHub issues/discussions, support channels | When the docs don't answer it and the status page is green |
1.2 Which to read first for a new service#
When you meet an API you have never used, the efficient order is almost always:
- Overview — what is this service for, and does it even do what you need?
- Authentication — can you even get a key, and what does it cost?
- Quickstart — get one call working end to end before reading anything else.
- The one reference page for the endpoint you need — not the whole reference.
- Rate limits and pricing — before you write the loop, not after the bill.
- Changelog and deprecations — skimmed once, so you know the docs have a history worth checking later.
Everything else (cookbooks, guides, SDK docs) is pulled in on demand, when the reference page raises a question it can't answer.
flowchart TD
A["New service: what do I need?"] --> B{"Have I made<br/>one successful call?"}
B -- "no" --> C["Overview → Auth → Quickstart"]
C --> D{"Call works?"}
D -- "no" --> E["Troubleshooting / errors guide<br/>(Part 6 of this lesson)"]
E --> C
D -- "yes" --> F["Read the reference page<br/>for YOUR endpoint only"]
B -- "yes" --> F
F --> G{"Does it loop,<br/>bill, or run in prod?"}
G -- "yes" --> H["Rate limits + pricing pages"]
G -- "no" --> I["Write the code"]
H --> I
I --> J{"Docs silent or behaviour<br/>differs from docs?"}
J -- "yes" --> K["Part 5: verify against<br/>SDK source, spec, status page"]
J -- "no" --> L["Done — note the docs version/date"]
K --> L1.3 How docs rot#
Documentation is code that nobody tests. Every docs site accumulates rot: examples copied from a two-year-old quickstart that still "look right" but use a retired parameter; a page last updated before the API's current version; a model name in an example that has since been deprecated; a response field shown that the API no longer returns. Three habits keep rot from biting you:
- Check the page's date. Many docs platforms show "Last updated" per page. GitBook, Mintlify and similar also expose page history. A page untouched for a year on a fast-moving API deserves suspicion.
- Check the version the docs describe. APIs are versioned (
anthropic-versionheaders,/v1/vs/v2/paths,v1betain Google's URLs). Docs sometimes mix versions on one page — the top of the page usually says which. - Prefer the machine-readable source when it exists. An OpenAPI spec or a
.mdtwin of the page is generated from the same source the API is built from; hand-written HTML examples are the first thing to go stale.
Part 2: Reading an API reference page#
2.1 The anatomy of a reference entry#
A well-written reference entry — one endpoint — answers, in roughly this order:
- The endpoint itself:
METHOD /path, the full URL including any version prefix (/v1/,v1beta), and the host. Some APIs put the resource in the path (/models/{model}:generateContent), others in the body ("model": "..."). - Authentication: which header carries the credential (
Authorization: Bearer,x-api-key,x-goog-api-key), and any extra required headers (anthropic-version, content type). - Parameters, grouped by where they travel: path (
{id}in the URL), query (?limit=20), header (X-Custom-Thing), body (the JSON you POST). For each: name, type, required or optional, default, allowed values (enums), and constraints (max length, minimum/maximum, pattern). - A request example: usually
curlplus SDK snippets. Check which language tab you're reading — examples differ subtly per SDK. - The response: the success schema and an example body. Look for which fields are always present vs optional, and which are
null-able. - Error responses: which status codes this endpoint returns, and the shape of the error body.
- Limits and caveats: rate limits specific to this endpoint, pagination style, beta/deprecated banners, "this parameter is ignored on model X" notes.
2.2 Worked reading: OpenAI — POST /v1/responses#
OpenAI's docs live at developers.openai.com. The docs index itself is published as llms.txt, and every page has a Markdown twin by appending .md to the URL — a gift when you want to feed a page to a tool or an assistant. The human reference is generated from the same OpenAPI specification OpenAI publishes at github.com/openai/openai-openapi (OpenAPI 3.1), which is also what their official SDKs are generated from.
For the Responses endpoint, the entry tells you:
- Endpoint:
POST https://api.openai.com/v1/responses, authAuthorization: Bearer <key>(lesson 03.1, 1.2 has the verified table). - Parameters:
model(required string — an ID from the models page, a volatile value),input(required: a string or a list of items),instructions,max_output_tokens,temperature-family sampling params,tools,text.formatfor structured output,stream,store,metadata,prompt_cache_key, and more — several dozen. The page marks each required/optional and gives types, enums and defaults. - Response: an object with
id,object: "response",status(completed,incomplete,failed...),output(a list of items: messages, tool calls, reasoning),usage(token counts), anderror/incomplete_detailswhen applicable. - Errors: the shared error envelope
{"error": {"message", "type", "param", "code"}}— the same shape across endpoints, documented once.
What the page doesn't lead with: that max_output_tokens truncation shows up as status: "incomplete", not an error — you find that in the response-field docs and in lesson 03.3. The reference is complete; the implications live in the guides. That split — reference for shape, guides for behaviour — is normal.
Illustrative request (needs a key; shown for reading practice only):
POST /v1/responses
{
"model": "gpt-6-luna",
"input": "Summarise this ticket in one sentence.",
"max_output_tokens": 120
}2.3 Worked reading: Anthropic — POST /v1/messages#
Anthropic's docs live at platform.claude.com/docs. The Messages API reference entry (/docs/en/api/messages/create) has the same skeleton with Anthropic's flavour:
- Endpoint:
POST https://api.anthropic.com/v1/messages. - Auth:
x-api-keyhistorically; SDK 2.x sendsAuthorization: Bearer. Plus the requiredanthropic-versionheader — a versioned API where2026-10-21removedtemperature,top_pandtop_k(a request sending them now gets a 400 — see lesson 03.1, 9.1). This is why "check the version" is not pedantry: the same parameter name can be valid on one version and rejected on another. - Parameters:
model(required),max_tokens(required — note: output cap, always required on Anthropic),messages(required array of{role, content}),system,tools,thinking,output_config,metadata. - Response:
id,type: "message",role: "assistant",content(a list of blocks:text,thinking,tool_use),stop_reason(end_turn,max_tokens,tool_use,refusal...),usage. - Notable difference in style: Anthropic's docs are famously precise about which fields appear when — e.g.
stop_reason: "refusal"is documented with its ownstop_details, because a refusal is an outcome you must handle, not an error.
2.4 Worked reading: Gemini — :generateContent#
Google's Gemini docs live at aistudio.google.com/docs (mirrored at ai.google.dev/gemini-api). Two things mark them as Google-style:
- The endpoint embeds the model:
POST https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent— the model is a path parameter, the action follows a colon. Auth isx-goog-api-key, not a Bearer header. Google's REST conventions (colon-actions,$discoverydocuments) differ from the OpenAI-style conventions the rest of the industry copied. - Two API families:
generateContent(the original) andinteractions(newer,/v1beta/interactions). The docs cover both; lesson 03.1, 5.3 explains which to use.
The API reference (aistudio.google.com/api-reference) is organised per-method. A generateContent entry shows contents (required array of {role, parts: [{text|inlineData|fileData}]}), systemInstruction, generationConfig (temperature, maxOutputTokens, responseMimeType, responseSchema...), tools, safetySettings. The response wraps everything in candidates[].content.parts[], with promptFeedback and usageMetadata alongside — fields that are easy to miss because the "answer" is nested two levels deep.
Gemini's docs are worth a second look here because they now describe two error vocabularies. For generateContent, errors come back in Google's standard REST error shape — {"error": {"code": <HTTP status as integer>, "message": ..., "status": "INVALID_ARGUMENT" | "RESOURCE_EXHAUSTED" | "NOT_FOUND" | ...}} — where status uses the gRPC-flavoured SCREAMING_SNAKE strings, documented with the method in the API reference and the $discovery document. The api-errors page covers the newer Interactions API instead: there the body is {"error": {"code", "message"}} with snake_case codes (invalid_request, authentication, rate_limit_exceeded, quota_exceeded, not_found...), delivered in the HTTP response or as an SSE event_type: "error" event when streaming. So: RESOURCE_EXHAUSTED on a generateContent call → the method reference's status list; rate_limit_exceeded on an Interactions call → the api-errors page. Same lesson as §2.1: the error vocabulary is part of which API family you're reading.
2.5 Worked reading: OpenRouter — POST /api/v1/chat/completions#
OpenRouter is the interesting case because it is a gateway: one API, hundreds of upstream models. Its docs (openrouter.ai/docs) are organised as guides plus a full API reference, and — unusually — the reference is generated from a public OpenAPI document at openrouter.ai/openapi.json (OpenAPI 3.1.0, verified November 2026), which also generates their official SDKs.
Reading a chat/completions entry, the OpenRouter-specific wrinkles to notice:
modelisvendor/model(anthropic/claude-haiku-5.5,openai/gpt-6-luna) — a volatile catalogue value; checkGET /api/v1/modelsor the models page, not a blog post.- Provider routing parameters (
providerobject: order, sort, allow_fallbacks, require_parameters) — OpenRouter-only fields layered onto the OpenAI-shaped request. - Attribution headers (
HTTP-Referer,X-OpenRouter-Title) — optional but they affect leaderboards. - Error semantics that differ from OpenAI's: OpenRouter documents a table of
error_typevalues on its errors-and-debugging page (rate_limit_exceeded,provider_overloaded,provider_unavailable), and its rate-limit page distinguishes credit limits (402), budget limits (403) and rate limits (429) — three different problems wearing similar HTTP codes.
The meta-lesson of the four readings: the skeleton is identical; the dialect is not. Same anatomy (endpoint, auth, params, request, response, errors), four different vocabularies for auth headers, versioning, model naming and error shapes. Once you can read one reference page fluently, the other three are a weekend, not a month.
2.6 What the docs don't say#
The most valuable skill in this part is noticing the gaps. Reference pages systematically omit:
- Behavioural implications. "
max_output_tokensreached" is documented as a finish reason; that it means you were billed for a truncated answer is not stated — you infer it fromusageplus the status. - Cross-parameter interactions. "This parameter is ignored when
stream=true", "this model doesn't support this feature" — sometimes in a footnote, sometimes only in an errors page, sometimes nowhere. - Version-specific behaviour. Which API version a default belongs to; what changed last release (that's the changelog's job — read it).
- The failure modes. Docs describe the happy path in detail and errors in a table; the combinations (rate limit + streaming + structured output) are yours to discover.
- What "required" really costs. A required parameter with no default means every call must compute it — design implication, not documented.
2.7 Reading rate-limit and pricing pages#
Step 5 of 1.2 says to read these pages before you write the loop. They are short, but they hide the numbers that decide whether your design works. Pull these items out of every rate-limit page and write them in your notes/ file (5.4):
| Extract | Why it matters | Example of what the page may say |
|---|---|---|
| The unit | Requests per minute (RPM) and tokens per minute (TPM) are different ceilings; LLM APIs usually enforce both, and tokens (02.2) are what usually bite first | "requests per minute", "input tokens per minute", "output tokens per minute" |
| The scope | A limit may apply per API key, per project, per organisation or workspace, or per model; scope decides whether two services sharing a key starve each other | "per organization", "per model" |
| The tier | Most providers raise limits as your account history or spend grows; your numbers are yours, shown in the dashboard, not the table in the docs | usage tiers, "request a higher limit" |
| How it is measured | A per-minute limit is often enforced continuously (a token-bucket style refill) rather than reset on the clock minute, so a burst at 12:00:59 can fail even though "the minute" looks unused | "token bucket", sliding window |
| What counts | Whether cached tokens, reserved output (max_tokens) or failed requests count against you changes the arithmetic (02.7, 6.4 explains why limits count tokens and how caching changes it) |
"counted when the request starts" |
| The signals | The status code (429), the headers that report remaining budget and reset time, and Retry-After — which you should obey rather than guess |
Retry-After: 2 |
| Spend and quota caps | A monthly spend cap or credit balance is a different failure from a rate limit (OpenRouter even uses a different status code, 2.5) | "monthly spend limit", "insufficient credits" |
| Batch and special queues | Batch and long-running APIs often have their own, separate limits | "separate limits for batch requests" |
Then do the arithmetic once, on paper. Suppose a provider allows 10,000 input tokens per minute and your prompts average 2,500 tokens: the ceiling is about four requests per minute whatever the RPM figure says, and eight parallel workers will hit 429 within seconds. That is the whole point of reading the page before the loop: it turns "why are we being throttled?" into a number you saw in advance. (Numbers here are illustrative; look up the real ones on the provider's page for your account.) What to do about a 429 — backoff, jitter, queues, concurrency caps — is 03.8 and 03.9; this lesson only teaches you to find the numbers.
Pricing pages repeat the pattern: find the unit (per million tokens, per image, per second of audio), whether input, cached input and output are priced separately, any tier or long-context surcharge, and the date the page was last changed. The ParcelPost docs show the same gap in miniature: "60 requests/minute per key; on 429 wait and retry" never says whether a Retry-After header is sent or how long to wait, so a careful client reads the header if present and otherwise backs off (01B.9) — and the notes file records "Retry-After: not documented".
Part 3: Machine-readable documentation: OpenAPI and friends#
Deep-dive
3.1 What an OpenAPI document is#
OpenAPI (the specification — version 3.2.x is current as of November 2026; the big providers' published specs still use 3.1, which is fully compatible for reading) is a standard, language-neutral way to describe a REST API as a JSON or YAML file. Where the HTML docs are for humans, the OpenAPI document is for machines: it is precise enough that tools can render documentation from it, validate requests against it, generate typed client libraries in any language, and — in the AI era — feed it to an assistant as ground truth.
The four parts you will actually read:
| Key | What it holds |
|---|---|
info |
Title, version, description of the API itself |
servers |
Base URLs the API is reachable at |
paths |
Every endpoint: "/shipments/{id}" → get/post/... → parameters, request body, responses |
components |
Reusable pieces: schemas (the shapes of requests and responses), securitySchemes (how auth works), parameters, responses |
Two conventions matter when reading one: parameters and requestBody describe what you send; responses describes what you get back, keyed by status code. A $ref: "#/components/schemas/Shipment" is a pointer to a named schema defined once under components — the same deduplication idea as YAML anchors.
3.2 Reading one for real#
JSON Schema inside OpenAPI can look intimidating, but you only need a subset: type, properties, required, enum, items (for arrays), minimum/maximum, format, and $ref. The lesson's fictional ParcelPost API publishes an OpenAPI document (8.6 has the whole file); this stdlib-only script prints its skeleton — the same information the rendered docs page shows, minus the prose:
# read_openapi.py — parse an OpenAPI JSON file with the standard library only
import json
import sys
def describe_parameter(p):
schema = p.get("schema", {})
bits = [p["name"], f"in={p['in']}",
"required" if p.get("required") else "optional",
schema.get("type", "?")]
if "enum" in schema:
bits.append("one of " + "/".join(schema["enum"]))
if "default" in schema:
bits.append(f"default={schema['default']!r}")
return " ".join(bits)
def main(path):
spec = json.load(open(path))
info = spec["info"]
print(f"{info['title']} {info['version']} (OpenAPI {spec['openapi']})")
print("servers:", ", ".join(s["url"] for s in spec.get("servers", [])))
schemes = spec.get("components", {}).get("securitySchemes", {})
print("auth:", ", ".join(f"{k} ({v.get('type')}/{v.get('scheme', v.get('name', '?'))})"
for k, v in schemes.items()) or "none")
for route, item in spec["paths"].items():
for method, op in item.items():
if method not in ("get", "post", "put", "patch", "delete"):
continue
print(f"\n{method.upper()} {route} — {op.get('summary', '')}")
for p in op.get("parameters", []):
print(" param:", describe_parameter(p))
if "requestBody" in op:
print(" body : required" if op["requestBody"].get("required")
else " body : optional")
if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else "parcelpost_openapi.json")ParcelPost API 1.2.0 (OpenAPI 3.1.0)
servers: https://api.parcelpost.example/v1
auth: bearerAuth (http/bearer)
GET /quotes — Price a shipment
param: to_postcode in=query required string
param: weight_g in=query required integer
param: service in=query optional string one of economy/standard/express default='standard'
GET /shipments — List shipments (cursor-paginated)
param: limit in=query optional integer default=2
param: cursor in=query optional string
POST /shipments — Create a shipment
body : required
GET /shipments/{id} — Fetch one shipment
param: id in=path required stringThat is the whole API in eighteen lines of output — every endpoint, every parameter with its location, requiredness, type, enum and default. When a docs page is ambiguous, the spec is the tiebreaker; when the spec and the page disagree, the running API is the final tiebreaker (5.1).
3.3 Which providers publish specs (verified)#
| Provider | Machine-readable spec | Where | Notes |
|---|---|---|---|
| OpenAI | Official OpenAPI 3.1 spec, YAML + JSON | github.com/openai/openai-openapi — openapi.yaml / openapi.json, generated artifacts synced from upstream |
Official SDKs are generated from it |
| OpenRouter | Official OpenAPI 3.1.0 spec | openrouter.ai/openapi.json and .yaml, live |
Powers their @openrouter/sdk (Speakeasy-generated) and the openrouter Python package |
| Gemini | Google Discovery document + an OpenAPI 3.0 view | https://generativelanguage.googleapis.com/$discovery/rest?version=v1beta and .../$discovery/OPENAPI3_0?version=v1beta — no API key needed (as of November 2026) |
Google's house style: protobuf-derived discovery docs, OpenAPI as a view |
| Anthropic | No official public spec at a stable URL | SDKs are Stainless-generated; a community mirror of the hosted spec snapshot exists at laszukdawid/anthropic-openapi-spec |
Unofficial and possibly stale — the docs remain the contract |
3.4 Swagger UI, Redoc, and generating clients#
An OpenAPI document is useless until something renders or consumes it:
- Swagger UI — the classic interactive explorer: paste a spec URL, get a page where you can fill in parameters and fire real requests from the browser. Many providers host one; you can also run it locally against any spec file.
- Redoc — a cleaner read-only renderer, popular for documentation sites (Stripe-style three-column layout). Good for reading; Swagger UI is better for trying.
- Code generators — OpenAPI Generator,
openapi-typescript,datamodel-code-generatorand friends turn a spec into typed clients in dozens of languages. This is how most official SDKs are born; it is also how you can generate a client for an internal API your team documents but doesn't ship an SDK for.
Your own APIs produce specs for free: FastAPI generates an OpenAPI document from your Python type hints and serves it at /openapi.json with interactive docs at /docs — lesson 01B.7 builds this, and lesson 11C.1 shows it being switched off in production. The same skill — read the spec, not just the prose — is what you will use on your own services when another team integrates with them.
3.5 llms.txt and docs for machines#
A newer convention, llms.txt (a community proposal; the spec is at llmstxt.org, currently at v2), asks sites to publish a curated Markdown index at /llms.txt so that AI agents — and engineers feeding docs to assistants — can discover the canonical pages instead of scraping navigation chrome. Many docs platforms generate one automatically, and several offer .md twins of every page.
Verified as of November 2026, all four providers in this path publish machine-readable doc indexes:
| Provider | Docs index for machines |
|---|---|
| OpenAI | developers.openai.com/llms.txt — a top-level index that links to per-product indexes (the API guides and reference have their own llms.txt under /api/), with .md pages and full-document exports; follow the file's own links for the current names |
| Anthropic | platform.claude.com/llms.txt + .md twins |
| Gemini | aistudio.google.com/llms.txt + llms-full.txt |
| OpenRouter | openrouter.ai/docs/llms.txt, with bulk _llms/docs.txt and _llms/api-reference.txt files |
Lesson 05.3, 4.2 covers llms.txt from the ingestion side — parsing it, when to prefer it over scraping. Here the point is narrower: when you point an assistant at docs, point it at the llms.txt or the .md page, not the rendered HTML. The Markdown version is smaller, cleaner, and far less likely to be mangled into nonsense by a summariser.
3.6 Docs MCP servers and doc-search tools#
The newest entry on the docs map: providers now host MCP servers that expose their own documentation to any MCP-capable assistant. Verified as of November 2026:
| Provider | Docs MCP server | What it offers |
|---|---|---|
| OpenAI | https://developers.openai.com/mcp (streamable HTTP, no auth) |
Search + read OpenAI developer docs; documentation only, not the API itself |
| Anthropic | https://platform.claude.com/docs/mcp (streamable HTTP, no auth) |
Tools: search_docs, get_navigation, get_doc, get_api_endpoint — the last returns parameters, request bodies and responses for a specific endpoint |
| Gemini | https://gemini-api-docs-mcp.dev — a remote server listed as "Gemini Docs MCP server" under "Agent setup & developer tooling" in Google's own llms.txt for the Gemini API docs (https://aistudio.google.com/llms.txt, opened November 2026); the server's own page does not say who operates it, and there are also community docs servers for Gemini, so check that you are connecting to the address Google lists |
Search and read Gemini API docs |
| OpenRouter | No official docs MCP server found as of November 2026 — its llms.txt lists docs and SDKs only |
Use llms.txt / .md pages instead |
MCP itself — the protocol, transports, security — is lesson 08E.1's subject; third-party doc-search servers (community-maintained indexes of many libraries' docs) follow the same pattern. The engineering caution is identical either way: a docs MCP server is a very fast way to get a plausible, confidently-stated wrong answer about an API. It reduces retrieval errors, not reasoning errors — Part 7 is the verification routine that makes it safe.
Part 4: SDK docs versus REST docs#
4.1 SDK docs are a layer over the REST docs#
Every official SDK is a typed, ergonomic wrapper around the same HTTP API the reference documents. The mapping is almost mechanical:
| REST reference says | SDK docs say |
|---|---|
POST /v1/messages with a JSON body |
client.messages.create(model=..., max_tokens=..., messages=[...]) |
Parameter max_tokens (integer, required) |
Argument max_tokens: int (required, no default) |
Response object with content[] blocks |
message.content — a list of typed TextBlock/ToolUseBlock objects |
Error envelope {"error": {...}} |
Typed exceptions: RateLimitError, AuthenticationError, NotFoundError... |
X-RateLimit-* headers |
response.headers or SDK-specific rate-limit objects |
Pagination via cursor/has_more |
.iter_pages() / auto-pagination helpers |
Two consequences for reading:
- Learn the REST shape first, then the SDK sugar. The SDK hides the wire; when something behaves unexpectedly (a header you can't see, a retry you didn't write), the REST docs are the ground truth. Lesson 03.1, 1.3 literally shows you the wire each SDK produces.
- SDK docs are where provider-specific helpers live. Parse helpers (
responses.parse,messages.parse), streaming helpers (messages.stream), pagination helpers and retry configuration are SDK-layer features the REST reference doesn't cover — read the SDK docs for those, the REST reference for the data itself. Lesson 03.4 and 03.11 catalogue them per provider.
4.2 The documentation inside your editor#
Before you ever open a docs page for a library you already installed, three instruments answer most questions:
help()—help(client.messages.create)prints the docstring: signature, parameter descriptions, return type. Instant, offline, always matches the installed version — which is the point: docs websites describe latest, your environment has pinned.- Type hints — modern SDKs are fully typed; your IDE's hover shows parameter names, types and defaults as you type. A wrong argument name is a red squiggle before it is a runtime error.
dir()/ autocomplete — "what methods does this object have?" is one keystroke away.
help() needs no API key and makes no network call — it reads the installed package, so it always describes the version you run. When you haven't built a client, ask the resource class instead of instantiating one:
>>> from anthropic.resources.messages import Messages
>>> help(Messages.create) # doctored excerpt — your version may differ
Help on function create in module anthropic.resources.messages.messages:
create(self, *, max_tokens: int, messages: Iterable[MessageParam],
model: ModelParam, ...) -> Message(With a client, help(Anthropic(api_key="sk-ant-...").messages.create) prints the same docstring — constructing the client stores the key locally and calls nothing.)
4.3 Reading a library like its source#
When docstrings run out, the source code is the final authority — and it is more readable than its reputation:
- Repository layout:
src/<package>/for the code,README.mdfor the pitch,CHANGELOG.mdfor history,docs/or a docs site for prose,tests/for executable examples of intended behaviour — often the best documentation of edge cases. - README: what it is, install, 30-second example, links. Read it first for any new library.
- CHANGELOG / releases: what changed per version — the single most under-used file in open source. 4.4 is about reading it before you upgrade.
- PyPI page (
pypi.org/project/<name>/): current version, release history with dates,Requires-Python, classifiers, project links, download stats. The "is this library alive?" check: a release within the last few months, responsive issues, a real maintainer. - Issues and discussions: where the docs are silent, someone has usually asked. Search the repo's issues for the parameter name you're unsure about — the answer is often a maintainer's comment, which is documentation with a name and a date attached.
4.4 Versions, changelogs and deprecation warnings#
Version numbers follow semantic versioning (MAJOR.MINOR.PATCH, semver.org): a major bump means something may break, minor means new features, patch means fixes. For libraries, read the changelog before upgrading — a "minor" release of an SDK can still change default behaviour, and LLM SDKs in particular ship fast (the pinned versions in this path — openai 3.42.1, anthropic 2.4.0, google-genai 2.34.0 — will look dated within months; that is normal).
Inside Python itself, deprecation surfaces three ways, all worth recognising:
DeprecationWarning— printed bywarningswhen you run withpython -W defaultor in tests; means "this works now, will break later".- Docstring
.. deprecated::directives — visible inhelp()output. - Changelog entries — the authoritative record; warnings only cover what the library chose to flag.
Commands that answer "what's installed and what's available": pip index versions <pkg> (needs network), uv pip show <pkg> / uv pip list (your environment), pip show <pkg> (same, older tool). None of these upgrade anything — they only report, which is exactly what you want when checking facts.
Reading a migration guide. Providers publish one whenever an API version or SDK major version breaks something; Anthropic's guide for API version 2026-10-21 is a good model. A good one is organised by who is affected: each change opens with a line such as "Affects you if you send temperature, top_p or top_k", then says exactly what now fails and what to do instead. Work through it like a checklist: (1) search your own code for each "affects you if" condition and mark the ones that apply, (2) change the version header or upgrade the SDK as a deliberate step, not by accident, (3) fix the marked items, and (4) run your tests and a few real calls before deploying. Anything that does not apply is not busywork to skip silently: note "checked, not affected" so the next upgrade starts from known ground.
Part 5: Verifying what the docs say#
5.1 Docs versus reality#
Documentation and implementation drift apart constantly — the page was written for version N, the API runs version N+3. Real discrepancies this path has already documented:
- Anthropic's auth header: docs and old examples lead with
x-api-key; SDK 2.x sendsAuthorization: Bearer. Both work, but a proxy written against the docs' header breaks on the SDK's requests (03.1, 1.2). - SDK schema transforms: OpenAI's strict mode requires every field; your Pydantic model's
Optionalfields are rewritten before sending. The docs describe the API; the SDK docs describe the transform (03.4, 2.9). - Silent no-ops: Gemini's SDK accepts
maxLengthin a schema and silently doesn't enforce it — the docs' "supported subset" table is the only warning (03.4, 4.4). - Volatile values: a model name or price copied from a blog post is wrong within weeks (5.3).
The verification habit is a loop, not a vibe:
- Find the claim — the exact parameter, field, limit or behaviour.
- Rank the sources — running API > official spec/SDK source > official docs > changelog > blog/forum.
- Run the smallest possible experiment — one request with the parameter in question, or
help()/source inspection for SDK behaviour. No key? The local stand-in in 03.1, Part 12 answers most questions about shape, though not about hosted-only features. - Write down what you confirmed, with the date — 5.4.
5.2 The source-reliability checklist#
Before trusting any API claim, ask:
| Question | Reliable answer lives in |
|---|---|
Is this the official domain? (developers.openai.com, platform.claude.com, aistudio.google.com/ai.google.dev, openrouter.ai) |
The URL itself — check it, don't assume a lookalike |
| What version does this describe? | The page's version banner, anthropic-version-style headers, the spec's info.version |
| When was it written/updated? | "Last updated" stamps, git history on docs repos, changelog dates |
| Does it match the machine-readable source? | The OpenAPI spec, the .md twin, the SDK's type hints |
| Is the service even up? | The status page (03.8, 12.2 lists all four) |
| Do practitioners confirm it? | Official GitHub issues/discussions, the provider's forum — weighted by who answers (maintainer > user) |
A blog post, tutorial or video is a lead, never a source: useful for discovery ("oh, this parameter exists"), useless for detail ("it defaults to X"). The moment a claim matters — money, correctness, security — it must trace to an official page you can cite.
5.3 Volatile facts: model names, prices and limits#
Some facts change faster than any documentation can be kept accurate: model IDs, prices, rate limits, context windows, deprecation dates. The durable skill is knowing where the live value lives and how to date your notes:
- Model lists and capabilities: each provider's Models API (
GET /v1/modelson OpenAI and Anthropic,models.liston Gemini,GET /api/v1/modelson OpenRouter) — machine-readable, always current. Lesson 02.9, 4.10 shows the calls; 02.9, 4.9 works the OpenRouter catalogue live. - Prices: the official pricing pages only — human-readable, no API. Lesson 03.7, 4.4 catalogs every source and the dated-snapshot discipline.
- Deprecation dates: the deprecations pages — OpenAI's
/api/docs/deprecations, Anthropic'smodel-deprecations(with its Active → Legacy → Deprecated → Retired lifecycle), Gemini's/docs/deprecations(deprecated vs shutdown dates).
The habit: write "as of " next to every volatile fact you record, and re-verify on a schedule — 02.9, 1.5 makes the same durable-vs-dated split for the whole model landscape.
5.4 Keeping a notes file of verified facts#
Your ai-path workspace (00.1 creates it, 00.3 makes it a git repo) already has a notes/ folder for exactly this. One file per service, one line per fact, each with the date you verified it and where:
<!-- notes/parcelpost.md — fictional example from Part 8 -->
# ParcelPost API — verified facts
- Base URL: https://api.parcelpost.example/v1 — docs, checked 2026-11-06
- Auth: `Authorization: Bearer <key>` — docs "Authentication" page, checked 2026-11-06
- `service` enum is economy|standard|express — reference page AND openapi.json agree, checked 2026-11-06
- Max weight 30,000 g — verified by POST returning 422 invalid_fields, checked 2026-11-06
- Pagination: `cursor` param, `next_cursor` null at end — verified by listing 3 shipments, checked 2026-11-06
- NOT verified: whether `price_pence` includes VAT — docs silent; ask support before invoicingTwo rules make the file worth having: only write what you verified (a guess in the notes file becomes a bug with a citation), and re-verify on a trigger — a docs page change, an SDK upgrade, a support ticket, or a quarterly skim.
5.5 Copying examples responsibly#
Quickstart code is written to be read, not deployed. When you adapt an example:
- Strip the secrets. Examples contain
sk-...-style placeholders or, worse, real leaked keys — never paste a key into source; it goes in.env(03.1, 3.4). - Check the version it targets. An example for
anthropic-version: 2023-06-01may use parameters the current version removed. - Add the missing half. Examples show the request; production needs timeouts, error handling, retries-with-care and logging (01B.9, 03.8).
- Licence awareness. Copying docs text is one thing; copying code from a tutorial into your product carries the author's licence — check it, or write the ten lines yourself (you understand them better anyway).
5.6 Which source answers which question#
"Verify everything" is useless advice without a map of what to verify against what. When a question comes up, the fastest correct source is almost always the most specific one that exists. This is the decision table for "which source answers which question":
| The question | Trust, in order |
|---|---|
| What is this parameter called, and what are its exact constraints? | API reference page → the OpenAPI/discovery spec if one exists → help()/SDK type hints |
| Does my installed version accept this? | help(), type hints, the SDK's source — never the website, which describes latest |
| What changed recently / is this deprecated? | Changelog → deprecations/migration page → SDK CHANGELOG |
| Is the model/endpoint/price I'm about to use still current? | The Models API or models page → official pricing page → deprecations page (all dated "as of") |
| Is the service failing, or is it me? | Status page first, then your request ID in the error body |
What does this error code/type mean? |
The provider's errors page → the endpoint's error table → the spec's response schemas |
| The docs are silent or self-contradictory | SDK source → community mirror spec (marked unofficial) → official issues/discussions → your own experiment |
| What did the assistant just tell me? | Nothing yet — run the 7.2 routine, then the row above for whichever source it cited |
The pattern underneath: specific beats general, machine-readable beats prose, official beats community, and live beats dated — in that order, every time.
Part 6: Errors as documentation#
Deep-dive
6.1 The error body is part of the API#
A well-designed API documents its errors as carefully as its successes. The universal shape is {"error": {...}} — and inside it, three fields do the work:
| Field | What it tells you | Example (ParcelPost, fictional) |
|---|---|---|
type / code |
The category and specific reason, stable strings you can switch on | "type": "validation_error", "code": "invalid_fields" |
message |
Human-readable detail — sometimes containing the offending field name | "weight_g must be 1..30000" |
request_id |
A unique ID for this request — quote it in support tickets | "req_0001" |
Each provider wraps this differently: OpenAI uses {"error": {"message", "type", "param", "code"}}; Anthropic {"type": "error", "error": {"type", "message"}}; Gemini splits by API family — generateContent returns {"error": {"code", "message", "status"}} with gRPC status strings (INVALID_ARGUMENT, RESOURCE_EXHAUSTED...) while Interactions returns {"error": {"code", "message"}} with the snake_case codes on its api-errors page (2.4); OpenRouter adds an error_type taxonomy on its errors-and-debugging page. Lesson 03.8 catalogues all four — what to retry, what never to.
The habit: read the error body before the status code alone. A 400 with invalid_api_key and a 400 with context_length_exceeded are different problems; the status code alone can't tell you which.
6.2 request-id headers: your paper trail#
Almost every API returns a request identifier — OpenAI x-request-id, Anthropic request-id, OpenRouter X-Generation-Id, Google request IDs in responses/metadata. It is the single most useful string in debugging: it is what support asks for, what logs should record, and what links your code's failure to the provider's logs.
Lesson 03.8, Part 12 has the full per-provider table of where each lives and how to capture it on every attempt, not just the last. The rule for this lesson: an error without a captured request ID is a support ticket you can't file. The ParcelPost client in Part 8 stores it on every ApiError for exactly this reason.
6.3 Reading a Python traceback as documentation#
When your code fails, the traceback is the error message's API reference: it names the file, the line, the function, and the exception type — read bottom-up (the last line is what happened; the lines above are how you got there). Three fields to extract every time:
- Exception type —
KeyErrorvsTypeErrorvsjson.JSONDecodeErrorare different bugs. - The offending value —
KeyError: 'max_tokens'means the dict lacked that key; the fix is upstream of the crash. - The call chain — which of your functions passed the bad value down.
Lesson 00.9 teaches debugging as a method, and 01A.8 goes deep on Python tracebacks and logging. For API work specifically, the traceback usually ends one layer early: the real error is in the response body your code didn't print — 03.10, Part 1 is the checklist.
6.4 Failure gallery: symptom → likely cause → where the answer lives#
The most common ways API integrations fail, and the docs page that resolves each. Read the error body's code/type first (6.1) — the same HTTP status covers several different problems.
| Symptom | Usually means | Where the answer lives |
|---|---|---|
401/403 on every call |
Auth header name or format wrong (Authorization: Bearer vs x-api-key vs x-goog-api-key), key from the wrong environment, or a required version header missing |
The provider's Authentication page → 03.1, 1.2 |
404 on a model or endpoint name |
Retired model, wrong casing, or wrong API version in the URL (v1 vs v1beta) |
Deprecations page → Models API for the live list |
429 |
Rate limit or quota or spend cap — three different problems; OpenRouter splits them across 402/403/429 | Error body's type/error_type + Retry-After header → the provider's rate-limits page |
400 naming a parameter you didn't send |
An API-version migration removed or renamed it | The migration guide linked from the versioning/deprecations page |
Works in curl, fails in the SDK (or vice versa) |
The SDK transforms the request — added headers, renamed fields, schema rewrites | SDK docs for the transform; REST reference for the wire truth (4.1) |
| JSON decode error on a "successful" call | The response isn't JSON — usually an HTML error page from a proxy, a captive portal, or a wrong base_url |
Print the raw body first; check base_url/Content-Type |
connection refused / timeout |
Wrong host or port, VPN/proxy in the way, or the service is down | Status page → your network → the servers/base-URL docs |
| Infinite loop on a list endpoint | You're testing the wrong end signal (items empty vs next_cursor: null) or misreading the cursor |
The endpoint's pagination docs — cursor semantics are contract, not convention |
| Docs page and SDK disagree | Docs rot, or the SDK is ahead/behind the website | Changelog + installed version (help(), pip show) → 5.1 |
| Assistant gave a parameter that doesn't exist | Fluent invention from stale training data | The 7.2 routine — never ship an unverified signature |
| Example from a tutorial fails | Copied verbatim: wrong version, missing header, hard-coded volatile value | The reference page for your version — quickstarts are sketches (1.3) |
The meta-rule: every row ends at a page, not a guess. If you can't point to the doc that authorised a behaviour, you haven't finished reading the docs.
Part 7: AI assistants for reading docs#
Deep-dive
7.1 What they're genuinely good at#
An assistant with docs access (a docs MCP server, a .md page pasted in, or llms.txt fetched) is excellent at the labour of documentation:
- Finding the right page in a 200-page docs site — "which page documents the
storeparameter?" - Summarising a long guide into the five facts you need.
- Explaining jargon — "what's the difference between
top_pandtemperature?" - Drafting a client call or a migration diff you then check line by line.
- Cross-referencing — "does this parameter exist on both the Responses and Chat Completions APIs?"
7.2 The verification routine#
Every assistant-produced API claim passes the same gate as a blog post — because that is what it is: a confident paraphrase of whatever it retrieved, possibly from an old version:
- Ask for the source. "Which page did you get that from?" A claim with no URL is a guess.
- Open the source yourself. The
.mdtwin or the MCP-served page — check the parameter name exactly (one wrong character and the call 400s). - Check the version and date. Assistants happily mix
2024and2026docs in one answer. - Run it. The smallest possible call — or the local stand-in — before it touches production.
- Check the signature against your installed SDK.
help()and type hints are version-true; the assistant's memory is not.
7.3 The confidently-wrong failure mode#
The characteristic failure is not refusal — it is fluent invention: a plausible parameter name (max_output_token for max_output_tokens), a real-looking model ID that doesn't exist, a temperature value on an API version that removed it, an error code from a different provider. The assistant isn't lying; it is pattern-completing from stale training data, and it sounds exactly as certain about a wrong answer as a right one.
Part 8: Integrate an unknown API from docs alone#
This is the capstone of the lesson: a service you have never heard of, documented only by the pages below, integrated with a real (fake) server and a real client. Everything you need is in this section — no account, no key, no network beyond localhost.
8.1 The scenario#
Your team has chosen ParcelPost, a fictional parcel-shipping API, for a feature that prints shipping labels. The vendor sent you a documentation link and nothing else. Your job: read the docs, write a client, prove it works.
8.2 The documentation, as the vendor wrote it#
ParcelPost API — Documentation (fictional, written for this lesson)
Base URL:
https://api.parcelpost.example/v1Authentication: every request needsAuthorization: Bearer <your API key>. Keys are issued in the vendor dashboard; test keys start withpp_test_. Content type: send and receiveapplication/json.Endpoints
Method & path Purpose Parameters GET /quotesPrice a shipment query: to_postcode(string, required),weight_g(integer grams, required),service(string, optional, defaultstandard)POST /shipmentsCreate a shipment body: to_postcode(string, required),weight_g(integer, required, 1–30000),service(string, optional, defaultstandard)GET /shipmentsList your shipments query: limit(integer, optional, default 2, max 5),cursor(string, optional)GET /shipments/{id}Fetch one shipment path: id(string, required)
servicemust be one ofeconomy,standard,express.GET /quotesreturns{price_pence, currency, eta_days, service}.POST /shipmentsreturns201with a shipment object{id, to_postcode, weight_g, service, status, price_pence, currency, tracking_url};statusstarts aslabel_created.GET /shipmentsreturns{items: [...], next_cursor}— passnext_cursorback ascursoruntil it isnull.Errors — every error is
{"error": {"type", "code", "message", "request_id"}}:
HTTP typeWhen 400 invalid_request_errorMalformed request (bad JSON, bad limit)401 authentication_errorMissing or invalid API key 404 not_found_errorUnknown route or unknown shipment id 422 validation_errorMissing/invalid fields ( codenames the rule)Quote
request_idin support tickets. Rate limit: 60 requests/minute per key; on429wait and retry.
The vendor also publishes an OpenAPI document at /openapi.json — the same contract in machine-readable form, reproduced in full in 8.6.
8.3 Reading it like a pro: what you noticed#
Applying 2.1's checklist, the things a careful reader extracts that a skimmer misses:
weight_gis in grams, integer — not kilograms, not a float. The1–30000bound is only in thePOSTrow;GET /quotesdoesn't restate it, so you check the OpenAPI spec (or assume the same bound) rather than guess.servicehas a default — optional means omit it, not send null.- Pagination is cursor-based, and
next_cursor: nullis the end signal — not an emptyitemslist. The docs say "until it isnull", which is the contract; a client that loops untilitemsis empty would make one extra request. POSTreturns201, not200— your client must accept 201 as success (00.6 covers status classes).- The error contract is uniform — one envelope for every failure, so one
exceptpath handles all of them;request_idis the support-ticket field. - What's NOT documented: whether
price_penceincludes tax, whethertracking_urlis stable, whatstatusvalues exist beyondlabel_created. Those go innotes/parcelpost.mdas unverified — the 5.4 habit starts here.
8.4 The client, written from the docs alone#
Before reading the solution, try it yourself — this is the skill the whole lesson builds to. Using only the 8.2 reference table (not the code below), write two functions in a scratch file:
get_quote(to_postcode, weight_g, service="standard")— build the query string, sendGET /v1/quotes, return the parsed JSON.create_shipment(to_postcode, weight_g, service="standard")— sendPOST /v1/shipmentswith a JSON body, return the parsed JSON.
Every choice is a docs decision: how to encode the postcode's space into a URL, which headers to send, how to turn the body into bytes, how to handle the documented error envelope. When you're done — or stuck — read on. The full client below is standard library only — urllib.request + json, no SDK exists for this fictional API anyway. Save as parcelpost_client.py:
# parcelpost_client.py — a stdlib-only client for the fictional ParcelPost API.
# Written in lesson 00.8 from the API reference alone: urllib.request + json,
# no third-party packages. Run against parcelpost_server.py.
import json
import os
import urllib.error
import urllib.parse
import urllib.request
BASE_URL = os.environ.get("PARCELPOST_URL", "http://127.0.0.1:8765")
API_KEY = os.environ.get("PARCELPOST_API_KEY", "pp_test_do_not_use")
class ApiError(Exception):
"""One failed API call, carrying everything the docs say an error has."""
def __init__(self, status, err):
self.status = status
self.type = err.get("type")
self.code = err.get("code")
self.request_id = err.get("request_id")
super().__init__(f"{status} {self.code}: {err.get('message')}")
def _request(method, path, body=None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(
BASE_URL + path, data=data, method=method,
headers={"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=10) as resp:
return resp.status, json.loads(resp.read())
except urllib.error.HTTPError as e:
payload = json.loads(e.read() or b"{}")
raise ApiError(e.code, payload.get("error", {})) from e
def get_quote(to_postcode, weight_g, service="standard"):
# urlencode turns "SW1A 1AA" into "SW1A+1AA" — raw spaces are illegal in a URL
qs = urllib.parse.urlencode({"to_postcode": to_postcode,
"weight_g": weight_g, "service": service})
return _request("GET", f"/v1/quotes?{qs}")[1]
def create_shipment(to_postcode, weight_g, service="standard"):
return _request("POST", "/v1/shipments",
{"to_postcode": to_postcode, "weight_g": weight_g,
"service": service})[1]
def get_shipment(shipment_id):
return _request("GET", f"/v1/shipments/{shipment_id}")[1]
def list_shipments(limit=2, cursor=None):
params = {"limit": limit}
if cursor:
params["cursor"] = cursor
return _request("GET", "/v1/shipments?" + urllib.parse.urlencode(params))[1]
def demo():
print("quote:", get_quote("SW1A 1AA", 500, "express"))
for pc in ["SW1A 1AA", "M1 1AE", "EH1 1YZ"]:
s = create_shipment(pc, 500, "express")
print("created:", s["id"], s["status"], "->", pc)
print("track:", get_shipment("ship_0001")["tracking_url"])
page1 = list_shipments(limit=2)
print("page1 next_cursor:", page1["next_cursor"],
"ids:", [i["id"] for i in page1["items"]])
page2 = list_shipments(limit=2, cursor=page1["next_cursor"])
print("page2 next_cursor:", page2["next_cursor"],
"ids:", [i["id"] for i in page2["items"]])
try:
create_shipment("SW1A 1AA", 99_999, "express") # over the 30 kg limit
except ApiError as e:
print(f"error: {e.status} {e.code} (request_id={e.request_id})")
try:
get_shipment("ship_9999") # does not exist
except ApiError as e:
print(f"error: {e.status} {e.code} (request_id={e.request_id})")
if __name__ == "__main__":
demo()8.5 Proving it works: a fake server and real output#
To run the client you need the API — so you build the smallest fake that honours the documented contract. parcelpost_server.py uses only http.server from the standard library, implements the four endpoints and the error envelope exactly as documented, and is deterministic (fixed IDs, no timestamps). Create it in the same folder as the client:
# parcelpost_server.py — a tiny fake 'ParcelPost' shipping API for lesson 00.8.
# Serves the fictional API documented in the lesson on 127.0.0.1 with an
# ephemeral port. Stdlib only. Deterministic: fixed ids, no timestamps.
# Run: python3 parcelpost_server.py (prints the base URL, Ctrl+C to stop)
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs
API_KEY = "pp_test_do_not_use" # fictional placeholder key from the docs
SERVICES = {"standard", "express", "economy"}
MAX_WEIGHT_G = 30_000
PAGE_MAX = 5
shipments = {} # id -> shipment dict, insertion-ordered
counter = {"ship": 0, "req": 0}
lock = threading.Lock()
def next_id(prefix):
counter[prefix] += 1
return f"{prefix}_{counter[prefix]:04d}"
def err(status, etype, code, message):
with lock:
rid = next_id("req")
body = {"error": {"type": etype, "code": code,
"message": message, "request_id": rid}}
return status, body
def price_pence(service, weight_g):
"""One price formula shared by /quotes and /shipments, so the two always agree."""
per_kg = {"economy": 90, "standard": 180, "express": 420}[service]
return round(150 + per_kg * (weight_g / 1000))
def shipment_json(s):
return {"id": s["id"], "to_postcode": s["to_postcode"],
"weight_g": s["weight_g"], "service": s["service"],
"status": s["status"], "price_pence": s["price_pence"],
"currency": "GBP", "tracking_url": s["tracking_url"]}
class Handler(BaseHTTPRequestHandler):
def _send(self, status, obj):
data = json.dumps(obj).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def _auth_ok(self):
return self.headers.get("Authorization") == f"Bearer {API_KEY}"
def _read_json(self):
n = int(self.headers.get("Content-Length") or 0)
try:
return json.loads(self.rfile.read(n) or b"{}")
except json.JSONDecodeError:
return None
def do_GET(self): # noqa: N802 (http.server API)
if not self._auth_ok():
return self._send(*err(401, "authentication_error",
"invalid_api_key", "Missing or invalid API key."))
u = urlparse(self.path)
q = {k: v[0] for k, v in parse_qs(u.query).items()}
parts = [p for p in u.path.split("/") if p]
if parts == ["v1", "quotes"]:
problems = []
if not isinstance(q.get("to_postcode"), str) or not q.get("to_postcode"):
problems.append("to_postcode is required (string)")
try:
weight = int(q.get("weight_g", ""))
except ValueError:
weight = None
if weight is None:
problems.append("weight_g is required (integer, grams)")
elif weight <= 0 or weight > MAX_WEIGHT_G:
problems.append(f"weight_g must be 1..{MAX_WEIGHT_G}")
if q.get("service", "standard") not in SERVICES:
problems.append(f"service must be one of {sorted(SERVICES)}")
if problems:
return self._send(*err(422, "validation_error", "invalid_fields",
"; ".join(problems)))
service = q.get("service", "standard")
return self._send(200, {"price_pence": price_pence(service, weight),
"currency": "GBP", "eta_days": 3,
"service": service})
if parts == ["v1", "shipments"]:
try:
limit = int(q.get("limit", "2"))
except ValueError:
return self._send(*err(400, "invalid_request_error",
"bad_limit", "limit must be an integer"))
if limit < 1 or limit > PAGE_MAX:
return self._send(*err(400, "invalid_request_error",
"bad_limit", f"limit must be 1..{PAGE_MAX}"))
try:
cursor = int(q.get("cursor", "0"))
except ValueError:
return self._send(*err(400, "invalid_request_error",
"bad_cursor", "cursor must be an integer offset"))
if cursor < 0:
return self._send(*err(400, "invalid_request_error",
"bad_cursor", "cursor must be >= 0"))
items = list(shipments.values())
page = items[cursor:cursor + limit]
nxt = cursor + limit
return self._send(200, {"items": [shipment_json(s) for s in page],
"next_cursor": str(nxt) if nxt < len(items) else None})
if len(parts) == 3 and parts[:2] == ["v1", "shipments"]:
s = shipments.get(parts[2])
if s is None:
return self._send(*err(404, "not_found_error", "shipment_not_found",
f"No shipment {parts[2]}."))
return self._send(200, shipment_json(s))
return self._send(*err(404, "not_found_error", "unknown_route",
f"No route {u.path}. See the API reference."))
def do_POST(self): # noqa: N802
if not self._auth_ok():
return self._send(*err(401, "authentication_error",
"invalid_api_key", "Missing or invalid API key."))
u = urlparse(self.path)
if u.path != "/v1/shipments":
return self._send(*err(404, "not_found_error", "unknown_route",
f"No route {u.path}. See the API reference."))
body = self._read_json()
if body is None:
return self._send(*err(400, "invalid_request_error", "bad_json",
"Request body is not valid JSON."))
problems = []
if not isinstance(body.get("to_postcode"), str) or not body["to_postcode"]:
problems.append("to_postcode is required (string)")
if not isinstance(body.get("weight_g"), int):
problems.append("weight_g is required (integer, grams)")
elif body["weight_g"] <= 0 or body["weight_g"] > MAX_WEIGHT_G:
problems.append(f"weight_g must be 1..{MAX_WEIGHT_G}")
if body.get("service", "standard") not in SERVICES:
problems.append(f"service must be one of {sorted(SERVICES)}")
if problems:
return self._send(*err(422, "validation_error", "invalid_fields",
"; ".join(problems)))
with lock:
sid = next_id("ship")
ship = {"id": sid, "to_postcode": body["to_postcode"],
"weight_g": body["weight_g"],
"service": body.get("service", "standard"),
"status": "label_created",
"price_pence": price_pence(body.get("service", "standard"),
body["weight_g"]),
"currency": "GBP",
"tracking_url": f"https://track.parcelpost.example/{sid}"}
shipments[sid] = ship
self._send(201, shipment_json(ship))
def log_message(self, *a): # quiet
pass
if __name__ == "__main__":
srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
print(f"ParcelPost fake API on http://127.0.0.1:{srv.server_port}")
srv.serve_forever()What it implements, mapped back to the docs:
GET /v1/quotes— validatesto_postcode,weight_g(integer, 1–30000 — the bound the prose states forPOSTbut the OpenAPI spec declares for both) andserviceagainst the enum; violations return422+invalid_fieldswith a message naming the rule. A valid call returns a computedprice_pence(deterministic formula:150 + per_kg * weight_kg,per_kg90/180/420 for economy/standard/express).POST /v1/shipments— the same validation on the body, returns201+ shipment.GET /v1/shipments— cursor pagination exactly as documented (limitmust be an integer in 1–5 — the docs name "bad limit" as a400case, so the fake rejects rather than silently clamps — andnext_cursorisnullat the end); a non-integer or negativecursoris also a400.GET /v1/shipments/{id}—404+shipment_not_foundfor unknown IDs; unknown routes get404+unknown_route.- Every failure carries the documented error envelope; a global
Authorization: Bearer pp_test_do_not_usecheck returns401.
demo.py starts the server in a thread and calls parcelpost_client.demo(). It binds an ephemeral port (127.0.0.1:0 — the OS picks a free port, so it can never collide with a leftover process) and hands it to the client through PARCELPOST_URL, the environment variable the client already reads — the same mechanism you'd use to point the client at a staging server:
# demo.py — run the fake ParcelPost server in a thread, then exercise the client.
import os
import threading
from http.server import ThreadingHTTPServer
import parcelpost_server
# Bind an ephemeral port — never a fixed one that might already be in use —
# then tell the client where the fake API lives *before* importing it:
# parcelpost_client reads PARCELPOST_URL when the module loads.
srv = ThreadingHTTPServer(("127.0.0.1", 0), parcelpost_server.Handler)
os.environ["PARCELPOST_URL"] = f"http://127.0.0.1:{srv.server_port}"
threading.Thread(target=srv.serve_forever, daemon=True).start()
import parcelpost_client # reads PARCELPOST_URL at import time — must come after it is set
parcelpost_client.demo()
# One probe the client's demo() doesn't cover: the docs cap `limit` at 5,
# and the fake enforces it — a 400, not a silent clamp.
try:
parcelpost_client.list_shipments(limit=99)
except parcelpost_client.ApiError as e:
print(f"error: {e.status} {e.code} (request_id={e.request_id})")
srv.shutdown()Run it:
python3 demo.pyquote: {'price_pence': 360, 'currency': 'GBP', 'eta_days': 3, 'service': 'express'}
created: ship_0001 label_created -> SW1A 1AA
created: ship_0002 label_created -> M1 1AE
created: ship_0003 label_created -> EH1 1YZ
track: https://track.parcelpost.example/ship_0001
page1 next_cursor: 2 ids: ['ship_0001', 'ship_0002']
page2 next_cursor: None ids: ['ship_0003']
error: 422 invalid_fields (request_id=req_0001)
error: 404 shipment_not_found (request_id=req_0002)
error: 400 bad_limit (request_id=req_0003)Every line maps to a documented behaviour: the quote's shape, 201-equivalent creation with label_created, cursor pagination terminating on null, and all three documented error paths — 422 for a field violation, 404 for an unknown ID, 400 for a malformed parameter — each surfacing its request_id. Two classic bugs are avoided on purpose, and both are docs-versus-reality gaps of the kind 5.1 describes: a postcode containing a space breaks the URL unless you encode it (urllib.parse.urlencode, the 00.6 percent-encoding rule), and a guessed ID prefix (shp_ instead of the ship_ the server actually returns) fails every lookup — copy IDs from responses, never from memory. The fake server shows the same lesson from the other side: the prose only states the 1–30000 weight bound for POST, so the server also applies it on GET /quotes because the OpenAPI spec in 8.6 declares it for both.
8.6 The OpenAPI twin#
The vendor's /openapi.json is the same contract in machine-readable form. Save the document below as parcelpost_openapi.json in the same folder, then run the 3.2 script on it — python3 read_openapi.py parcelpost_openapi.json (create read_openapi.py from 3.2 if you haven't already):
parcelpost_openapi.json — the vendor's OpenAPI document
{
"openapi": "3.1.0",
"info": {"title": "ParcelPost API", "version": "1.2.0",
"description": "Ship parcels. Fictional API used in lesson 00.8."},
"servers": [{"url": "https://api.parcelpost.example/v1"}],
"security": [{"bearerAuth": []}],
"components": {
"securitySchemes": {
"bearerAuth": {"type": "http", "scheme": "bearer",
"description": "API key as a Bearer token."}
},
"schemas": {
"Shipment": {
"type": "object",
"required": ["id", "to_postcode", "weight_g", "service", "status"],
"properties": {
"id": {"type": "string", "example": "ship_0001"},
"to_postcode": {"type": "string"},
"weight_g": {"type": "integer", "minimum": 1, "maximum": 30000},
"service": {"type": "string", "enum": ["economy", "standard", "express"]},
"status": {"type": "string"},
"price_pence": {"type": "integer"},
"currency": {"type": "string"},
"tracking_url": {"type": "string", "format": "uri"}
}
},
"Error": {
"type": "object",
"required": ["error"],
"properties": {
"error": {
"type": "object",
"required": ["type", "code", "message", "request_id"],
"properties": {
"type": {"type": "string"},
"code": {"type": "string"},
"message": {"type": "string"},
"request_id": {"type": "string"}
}
}
}
}
}
},
"paths": {
"/quotes": {
"get": {
"operationId": "getQuote",
"summary": "Price a shipment",
"parameters": [
{"name": "to_postcode", "in": "query", "required": true,
"schema": {"type": "string"}},
{"name": "weight_g", "in": "query", "required": true,
"schema": {"type": "integer", "minimum": 1, "maximum": 30000}},
{"name": "service", "in": "query", "required": false,
"schema": {"type": "string", "enum": ["economy", "standard", "express"],
"default": "standard"}}
],
"responses": {
"200": {"description": "A price quote",
"content": {"application/json": {"schema": {
"type": "object",
"properties": {
"price_pence": {"type": "integer"},
"currency": {"type": "string"},
"eta_days": {"type": "integer"},
"service": {"type": "string"}}}}}},
"422": {"description": "Validation failed",
"content": {"application/json": {"schema": {
"$ref": "#/components/schemas/Error"}}}}
}
}
},
"/shipments": {
"get": {
"operationId": "listShipments",
"summary": "List shipments (cursor-paginated)",
"parameters": [
{"name": "limit", "in": "query", "required": false,
"schema": {"type": "integer", "default": 2, "maximum": 5}},
{"name": "cursor", "in": "query", "required": false,
"schema": {"type": "string"}}
],
"responses": {"200": {"description": "A page of shipments"}}
},
"post": {
"operationId": "createShipment",
"summary": "Create a shipment",
"requestBody": {
"required": true,
"content": {"application/json": {"schema": {
"type": "object",
"required": ["to_postcode", "weight_g"],
"properties": {
"to_postcode": {"type": "string"},
"weight_g": {"type": "integer", "minimum": 1, "maximum": 30000},
"service": {"type": "string",
"enum": ["economy", "standard", "express"],
"default": "standard"}}}}}
},
"responses": {
"201": {"description": "Shipment created",
"content": {"application/json": {"schema": {
"$ref": "#/components/schemas/Shipment"}}}},
"422": {"description": "Validation failed",
"content": {"application/json": {"schema": {
"$ref": "#/components/schemas/Error"}}}}
}
}
},
"/shipments/{id}": {
"get": {
"operationId": "getShipment",
"summary": "Fetch one shipment",
"parameters": [
{"name": "id", "in": "path", "required": true,
"schema": {"type": "string"}}
],
"responses": {
"200": {"description": "The shipment",
"content": {"application/json": {"schema": {
"$ref": "#/components/schemas/Shipment"}}}},
"404": {"description": "Unknown shipment",
"content": {"application/json": {"schema": {
"$ref": "#/components/schemas/Error"}}}}
}
}
}
}
}The script prints the whole contract in eighteen lines — the same output shown in 3.2 — and confirms two things the prose buried: weight_g's minimum/maximum bounds are declared in the schema on the quote parameters and the shipment body (the prose only implied them), and service's enum is identical across quote and shipment. When prose and spec disagree, the spec wins over the prose — the tiebreak order 5.1 teaches.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "I should read the whole docs site before writing code." | Read overview → auth → quickstart → your endpoint's reference page. The rest is pulled in on demand (1.2). |
| "The quickstart example is production-ready." | It is a sketch: it omits error handling, required headers added later, and hard-codes volatile values like model names (1.3). |
| "If it's not in the docs, it isn't allowed." | Undocumented often means unsupported — but also sometimes undocumented-but-working. Either way it isn't guaranteed; verify and note it (2.6). |
| "The SDK docs are the API docs." | The SDK is a layer over the REST API; the REST reference is the contract, SDK docs add helpers and transforms (4.1). |
| "An OpenAPI spec means the docs are complete." | The spec describes shape, not behaviour: pagination semantics, billing implications and cross-parameter rules still live in prose (3.1). |
| "All four providers publish an OpenAPI spec." | OpenAI and OpenRouter do; Gemini publishes discovery docs plus an OpenAPI view; Anthropic publishes no official public spec (3.3). |
| "The chatbot's API answer is reliable because it quoted a page." | It paraphrases whatever it retrieved, possibly an old version, and invents plausible details fluently. Verify every claim (Part 7). |
| "Docs vs reality disagreements mean the docs are useless." | They mean docs rot. The fix is a verification habit and a dated notes file, not cynicism (Part 5). |
| "A 4xx error means my request was wrong." | 429 is "slow down", 402/403 on OpenRouter are money problems, 404 can mean a retired model — read the error body, not just the class (6.1). |
| "I don't need request IDs; the error message is enough." | The request ID is what support uses to find your call; without it your ticket is unactionable (6.2). |
Key takeaways#
- Docs sites share a map: overview → quickstart → auth → concepts → API reference → SDK docs → changelog/deprecations → status/pricing → community. Read in that order, pull sections on demand.
- A reference entry has a fixed anatomy: endpoint, auth, parameters by location, request example, response schema, errors, limits, beta markers. Learn it once, apply it to every API.
- The skeleton is universal; the dialect is not — auth headers, versioning, model naming and error shapes differ per provider; the four worked readings show the pattern.
- Docs systematically omit implications — billing, cross-parameter interactions, version-specific behaviour. If it isn't written, it isn't guaranteed.
- Machine-readable docs beat prose when they exist: OpenAPI specs (OpenAI, OpenRouter, Gemini-discovery; not Anthropic),
llms.txtindexes (all four),.mdpage twins, and docs MCP servers — all verified November 2026. - SDK docs are a layer over REST docs: learn the wire shape first;
help(), type hints and docstrings are version-true documentation your editor already has. - Verify volatile facts against live sources: Models APIs for model lists, official pricing pages for prices, deprecations pages for retirements — always dated "as of".
- Read limits and prices before the loop: extract the unit (RPM/TPM), scope, tier, measurement, signals (
429,Retry-After) and caps, and do the arithmetic once. - Keep a
notes/file of verified facts with dates — only what you confirmed, re-verified on triggers. - Errors are documentation: read the error body's
type/code/message/request_id, capture request IDs on every attempt, and read tracebacks bottom-up. - AI assistants accelerate doc-reading but not doc-verification — the verification routine (source → version → run → SDK signature) is non-negotiable.
- The proof is a working client: the ParcelPost exercise shows the whole loop — docs → reference reading → client → fake server → real output — with nothing but the standard library.
Where you'll use this in the AI path#
- 03.1, 1.2-1.3: the verified endpoint/auth table for all four providers — this lesson's worked readings are the "how to read it" behind that table.
- 02.9, 1.5 and 4.9: the durable-vs-dated split and the live OpenRouter catalogue — where volatile model facts actually live.
- 03.7, 4.4: every source of truth for prices, and the dated-snapshot discipline this lesson's notes-file habit mirrors.
- 03.8, Part 12: the full request-ID and support-ticket practice built on this lesson's error-reading foundation.
- 03.4 and 03.11, Part 13: where SDK-docs-vs-REST-docs distinctions (schema transforms, parse helpers, library trade-offs) play out at full depth.
- 01B.7: FastAPI generating your own OpenAPI docs — the skill in reverse, when you are the provider.
- 05.3, 4.2 and 08E.1:
llms.txtfor ingestion pipelines and MCP for agent tooling — the machine-readable-docs thread continued. - 00.9: the debugging and learning habits this lesson's verification routine plugs into.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| API reference | The exhaustive per-endpoint documentation: parameters, request/response shapes, errors |
| Quickstart | The shortest documented path to a first successful API call |
| API family | A distinct request/response format under one provider (Responses vs Chat Completions; generateContent vs Interactions) |
| Path / query / header / body parameter | The four places an API parameter can travel |
| Endpoint | One method + URL pair in an API (glossary has the full entry) |
| OpenAPI | The standard language-neutral spec format for describing a REST API (JSON or YAML) |
paths / components / securitySchemes |
The OpenAPI keys holding endpoints, reusable schemas, and auth definitions |
$ref |
A JSON Schema pointer to a named definition elsewhere in the document |
| Swagger UI / Redoc | Interactive and read-only renderers for OpenAPI documents |
llms.txt |
A curated Markdown index a site publishes for AI agents and doc tooling (glossary) |
| Docs MCP server | An MCP server that exposes a provider's documentation to assistants for search and retrieval |
| Semantic versioning (semver) | MAJOR.MINOR.PATCH versioning where major bumps may break compatibility (glossary) |
| Deprecation / migration guide | The docs announcing a feature's removal and how to move off it |
| Status page | The provider's live incident and uptime page (glossary) |
| Volatile fact | A value that changes faster than docs can track: model IDs, prices, limits, dates |
| Source-reliability checklist | The ordered questions for deciding whether a doc claim can be trusted |
Request ID / request_id |
The per-request identifier for support and log correlation (glossary) |
| Error envelope | The uniform {"error": {...}} shape APIs use for failure responses |
| Cursor pagination | Pagination via an opaque cursor/next_cursor token rather than page numbers (glossary) |
| Docs rot | The gradual drift between documentation and the running API |
| RPM / TPM | Requests per minute and tokens per minute: the two usual rate-limit units for LLM APIs |
| Migration guide | A provider's step-by-step list of changes needed to move to a new API or SDK version, organised by who is affected |
All terms are also collected in the glossary.
Exercises#
Exercises 1, 4, 5, 6 and 7 need internet access to the providers' docs sites; the rest — including the whole ParcelPost exercise — run fully offline.
- Docs-site mapping. Pick any API you use (or one from this path: OpenAI, Anthropic, Gemini, OpenRouter). List its docs site's sections in the 1.1 table order, and note which section you would read first for a brand-new integration and why.
- Reference-entry anatomy. Take one endpoint from any provider's API reference and label each part with the 2.1 checklist numbers (endpoint, auth, parameters by location, request example, response, errors, limits). Which parts were hardest to find?
- What the docs don't say. Choose a parameter on a real endpoint. Find what the reference says about it, then list three things it does not say that you would need to know before using it in production.
- OpenAPI reading. Download
openapi.jsonfromopenrouter.ai(or use theparcelpost_openapi.jsonfile from 8.6) and run theread_openapi.pyscript on it. Pick one endpoint and compare the spec's parameter list against the human docs page — do they agree? - Spec availability. For each of the four providers, find where its machine-readable API description lives (or confirm none exists) using only 3.3's table and the linked pages. Which provider would be hardest to generate a typed client for, and why?
- Version check. Anthropic's
anthropic-version: 2026-10-21removedtemperature. Find the migration guide it links to and list two other breaking changes it documents. - Deprecation watch. On Anthropic's model-deprecations page, find one model with a scheduled retirement date in the next 90 days. What does the page say the lifecycle statuses mean, and what should a team do before the date?
- Notes file. Write a
notes/<service>.mdentry for one API you actually use, in the 5.4 format: five verified facts with dates and sources, plus one thing you could not verify. - Error reading. Trigger (or simulate) one error against the ParcelPost fake server — a 422, a 404, a 400 (
limit=99) or a 401 — and write down thetype,code,messageandrequest_idyou got. Which field would you quote in a support ticket? - AI-assistant audit. Ask an AI assistant for the correct parameter name and default for one real endpoint (e.g. OpenAI's
max_output_tokensvsmax_tokens). Then verify its answer against the official reference page andhelp()on the installed SDK. What did the verification catch? - Worked exercise. Complete the Part 8 exercise: create the files shown in 8.4–8.6 in a scratch folder, run
python3 demo.py, and confirm you get the output shown in 8.5. Then modifydemo()to create two more shipments before listing (five in total), and fetch and print a third page oflist_shipments(limit=2, ...). - Docs-versus-reality hunt. Find one place where docs and SDK behaviour differ in this path (hint: 5.1 lists four). Write a two-sentence note explaining which source you would trust and why.
Solutions
- Model answer: OpenAI's docs index (via
llms.txt) groups Guides, API reference, Changelog, Deprecations — a new integration reads Overview → Authentication → the relevant guide → the endpoint's reference page. Ordering differs per vendor; the principle (orientation → auth → one endpoint → limits) is constant. - Model answer: e.g. OpenAI
POST /v1/responses: endpoint+auth in the page header;model/input/instructions/max_output_tokensas body params with required/optional marks; curl + SDK examples; response object schema; shared error envelope; rate-limit note. Hardest: which response fields are always present vs optional — that lives in the schema'srequiredlist, not the prose. - Model answer: e.g.
storeon the Responses API: docs say it controls whether the response is stored; they don't say retention period, whether stored responses are trainable, or howstore:falseinteracts withprevious_response_id— those need the privacy docs and a test call. - Model answer: The OpenRouter spec lists every path/method with parameters;
read_openapi.pyprints them compactly. Discrepancies to look for: prose examples using deprecated fields, or spec enums the prose doesn't mention. - Model answer: OpenAI (GitHub repo), OpenRouter (live JSON/YAML), Gemini (discovery + OpenAPI3_0 view) publish specs; Anthropic does not at a stable URL — hardest to auto-generate a client for. A community mirror of the Stainless-hosted spec snapshot exists (
laszukdawid/anthropic-openapi-spec) but is unofficial and possibly stale. - Model answer: The migration guide (
platform.claude.com/docs/en/api/migration-2026-10-21) documents thetemperature/top_p/top_kremoval (400 error), a 400 for adocumentblock placed directly in anassistantmessage, a 400 for atextblock with a non-emptycitationsarray in ausermessage, and Admin API field renames (roles→role_ids,group_id→rbac_group_id,name→display_name). - Model answer (dates as on the page in November 2026 — re-check, they change, and after 30 November pick whichever row is then marked Deprecated): the page lists
claude-sonnet-4-5-20250929as Deprecated on 30 September 2026 with a retirement date of 30 November 2026 andclaude-sonnet-5-5as the recommended replacement; that falls inside the next-90-days window in early-to-mid November. The page promises at least 60 days' notice before retiring a publicly released model, and 30 September to 30 November is 61 days. A team on that snapshot migrates toclaude-sonnet-5-5and re-runs its evals first. (Active models carry a "not sooner than …" date instead — a tentative earliest retirement, not a promise of when.) Lifecycle: Active (supported) → Legacy (no updates) → Deprecated (still works, retirement date set) → Retired (requests fail). Action: test the replacement on your evals before the date, don't wait for the failure. - Model answer: See the 5.4 example — five dated facts with sources and one explicit "NOT verified" line.
- Model answer: e.g.
{"error": {"type": "validation_error", "code": "invalid_fields", "message": "weight_g must be 1..30000", "request_id": "req_0001"}}— quoterequest_id(andcode) in the ticket. - Model answer: Assistants commonly produce
max_tokens(Chat Completions name) where Responses wantsmax_output_tokens, or invent defaults. Verification: official reference page +help(client.responses.create)— catches both the name and the version. - Model answer:
mkdir parcelpost-ex && cd parcelpost-ex, create the files shown in 8.4–8.6 (parcelpost_client.py,parcelpost_server.py,demo.py,parcelpost_openapi.json, andread_openapi.pyfrom 3.2 for the spec check),python3 demo.py— output matches 8.5. For page 3: with five shipments andlimit=2the cursors run'2','4', thenNone, so page 3 holds justship_0005andnext_cursorisNone; awhile cursor:loop that followsnext_cursorfetches every page without you counting them. - Model answer: e.g. Anthropic auth: docs lead with
x-api-key, SDK 2.x sendsAuthorization: Bearer— trust the SDK's actual wire behaviour (and the API overview's "legacy fallback" note) for what your code sends.
Check yourself#
- What's the difference between a docs site's "guides" section and its "API reference" section, and which do you read first for a new endpoint?Guides teach concepts and behaviour; the reference is the exhaustive lookup for shape. For a new endpoint you read the reference page for that endpoint — guides are pulled in when the reference raises a question.
- List the four places an API parameter can travel, and give an example of each.Path (
/shipments/{id}), query (?limit=20), header (Authorization: Bearer,anthropic-version), body (JSON in POST/PUT/PATCH). - Why is "required" on a parameter not the same as "must send a value"?A field can be required-but-nullable (present, may be
null) — strict APIs use this to force the field to be addressed. Check the schema'srequiredlist. - Name the four providers' docs-site URLs and one machine-readable index each publishes.OpenAI
developers.openai.com(/llms.txt,.mdtwins); Anthropicplatform.claude.com(/llms.txt); Geminiaistudio.google.com(/llms.txt+llms-full.txt); OpenRouteropenrouter.ai/docs(/docs/llms.txt+ bulk_llmsfiles). - Which of the four providers does not publish an official public OpenAPI spec, and where does its SDK spec actually live?Anthropic — no official public spec at a stable URL; its SDKs are Stainless-generated, and a community mirror of the hosted spec snapshot exists (
laszukdawid/anthropic-openapi-spec) but is unofficial and possibly stale. - What does
llms.txtgive you that the rendered HTML docs page doesn't?A curated Markdown index of canonical pages (plus.mdtwins) — smaller, cleaner, machine-readable, no navigation chrome; the right input for tools and assistants. - How does an SDK's documentation relate to the REST API reference underneath it — and when do they legitimately disagree?The SDK wraps the REST API: method names map to endpoints, typed objects to JSON shapes, exceptions to error envelopes. They disagree when the SDK transforms (OpenAI required-fields rewrite, Anthropic moved constraints into descriptions) or adds helpers the REST API lacks — the REST reference is the contract.
- What's the difference between semantic versioning's MAJOR, MINOR and PATCH bumps, and why read a changelog before upgrading?MAJOR = breaking changes allowed; MINOR = new features, backward compatible; PATCH = fixes. Read the changelog first because "minor" SDK releases can still change defaults or signatures, and LLM SDKs ship fast.
- Give three questions from the source-reliability checklist and what a reliable answer looks like for each.e.g. official domain? (check the URL); what version? (page banner /
info.version/ API-version header); when updated? (last-updated stamp, changelog date); does it match the spec? (OpenAPI/.mdtwin/SDK hints); is the service up? (status page); do maintainers confirm? (official issues/discussions). - Which facts are "volatile" and where does each live (model IDs, prices, deprecation dates)?Model IDs (Models APIs / models pages), prices (official pricing pages only), rate limits (provider rate-limit pages/APIs), deprecation dates (deprecations pages) — all "as of " in your notes.
- What three fields in an API error body matter most, and what is
request_idfor?type/code(stable machine-readable reason),message(human detail),request_id(the per-request ID you quote in support tickets and log for correlation). - Describe the verification routine for an AI assistant's API claim in four steps.Ask for the source URL → open it yourself → check version and date → run the smallest call (or check
help()/SDK signature) before trusting it. - In the ParcelPost exercise, why does the client use
urllib.parse.urlencodefor query parameters?Because query strings can't contain raw spaces or reserved characters —urlencodepercent-encodes them (SW1A 1AA→SW1A+1AA), which is the 00.6 URL-encoding rule. - What does
next_cursor: nullsignal in the ParcelPost list endpoint, and what bug does looping untilitemsis empty cause?next_cursor: nullmeans no more pages — it is the documented end signal. Looping untilitemsis empty makes one extra request that returns an empty page (and may confuse code that treats empty as an error).
Further resources#
- OpenAI docs: developers.openai.com/api/docs — with
llms.txt,.mdtwins, changelog, deprecations, rate limits, and the Docs MCP server. OpenAPI spec: github.com/openai/openai-openapi. - Anthropic docs: platform.claude.com/docs —
llms.txt, API reference, model deprecations, API versioning, rate limits, and the docs MCP server. - Gemini docs: aistudio.google.com/docs —
llms.txt+llms-full.txt, deprecations, rate limits, API errors, pricing, API reference ataistudio.google.com/api-reference, discovery docs atgenerativelanguage.googleapis.com/$discovery/rest?version=v1beta, and the docs MCP atgemini-api-docs-mcp.dev. - OpenRouter docs: openrouter.ai/docs —
llms.txt, API reference, OpenAPI spec (.yamltoo), limits, errors and debugging, FAQ. - Specifications and conventions: OpenAPI Specification (3.1/3.2),
llms.txtspec, Semantic Versioning, Swagger UI and Redoc for rendering specs. - Status pages: status.openai.com, status.claude.com, aistudio.google.com/status, status.openrouter.ai.
- Later lessons in this path: 03.1 first API calls, 03.4 structured output, 03.7 cost and caching, 03.8 errors and retries, 03.10 debugging, 03.11 provider-agnostic client, 02.9 model landscape, 05.3 docs parsing, 08E.1 MCP.
← 00.7 — SQL Basics with SQLite | Module 00 overview | 00.9 — Working Like an Engineer: Debugging, Asking for Help and Learning Habits →