Free Python developer course
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
A machine-readable contract for docs, SDKs and AI tools.
What can a client generator learn about your API before a request runs?
An OpenAPI document describes operations, input parameters, and possible responses. Client code and tests can use the same contract to detect incompatible behavior.
The contract defines GET /reviews with a limit query parameter
A generator reads its name, type, and bounds
The generated client exposes a typed limit argument
The contract defines GET /reviews with a limit query parameter
A generator reads its name, type, and bounds
The generated client exposes a typed limit argument
Given The contract defines GET /reviews with a limit query parameter and The generated client exposes a typed limit argument, write down the missing step that connects them.
A generator reads its name, type, and bounds
Now take A generator reads its name, type, and bounds and the result above. Write an input and an implementation that could produce this trace.
The contract defines GET /reviews with a limit query parameter. Check that your implementation produces the result shown above.
If the server changes the successful response body from an array to an object, what should a contract check reveal?
It should flag a schema mismatch. Clients built against the array may fail even when the status remains 200.
A response gains an optional field while all existing fields and types stay the same. What concrete test supports the compatibility claim?
Run an unchanged old client against the new service and exercise both success and error responses. A strict client can still reject unknown fields, so do not assume compatibility from the schema change alone.
Check this when debugging. Hand-writing docs that drift away from the real API.
Documentation written by hand drifts from the code within weeks. OpenAPI is a description of an API that machines can read, and tools build almost everything from it: interactive docs, client libraries in many languages, tests, mock servers. The official Anthropic and OpenAI SDKs are generated from OpenAPI specs. It also makes an API usable by AI, because each operation maps neatly onto a tool definition for a model, or onto an MCP server.
It no longer matches what the code actually does
Hand-written docs drift as the code changes. An OpenAPI description generated from the code, or checked against it, stays in step, and tools build docs, clients and tests from it.
This rests on Validating requests with schemas: the schemas inside a spec are the JSON Schema you already read.
Think of a restaurant menu. It lists every dish, the choices you can make and what you'll get. An OpenAPI document (formerly called Swagger) does that for an API, written in JSON or YAML, which is a tidier way to write the same structure. Its paths section lists every endpoint, and under each, its methods, called operations:
{
"openapi": "3.1.0",
"info": {"title": "Shop API", "version": "1.4.0"},
"paths": {
"/campaigns/{campaign_id}": {
"get": {
"operationId": "get_campaign",
"summary": "Get one campaign by id.",
"parameters": [
{
"name": "campaign_id",
"in": "path",
"required": true,
"schema": {"type": "string"}
}
],
"responses": {
"200": {"description": "The campaign"},
"404": {"description": "No such campaign"}
}
}
}
},
"components": {
"securitySchemes": {"apiKey": {"type": "http", "scheme": "bearer"}}
}
}
Here's how to read it:
operationId is a unique name for the operation, like a dish's number on the menu. Code generators turn it into a method name, so client.get_campaign(...).parameters say where each value goes: "in": "path", "query" or "header", with a JSON Schema for each.requestBody holds the body's schema. responses maps status codes to what comes back.components stores reusable pieces: shared schemas, and how authentication works.Since version 3.1, the schemas inside are plain JSON Schema, the same language as your validator and Claude's tool input_schema.
schema = {
"type": "object",
"required": ["name"],
"properties": {"name": {"type": "string"}, "budget": {"type": "integer"}},
}
body = {"budget": 250}
missing = [field for field in schema["required"] if field not in body]
print(missing, sorted(schema["properties"]))['name'] ['budget', 'name']
The schema knows two fields and requires one of them, and the body leaves that one out. An OpenAPI document is made of schemas like this, with the paths, the methods and the status codes written around them. One document then describes the whole API.
?status=active?"in": "query"
"in" can be path, query, header or cookie. Path parameters are always required.
An architect's drawing does a lot of jobs. The builder, the electrician and the inspector all work from the same sheet. A spec, the OpenAPI document for your API, is that sheet:
In plain words: write one accurate description of your API, and let tools produce the rest from it.
The words that make a good operation are the words a model reads when it picks a tool.
Write a sentence or two, then compare it with a good answer in the lesson.
A framework already knows every route, so a spec can be generated from the code, and a tool list can be generated from the spec.
You can build a shed and sketch it afterward, or draw it first and show the family before you buy any wood. APIs offer the same choice:
/openapi.json, with docs at /docs.Code first is faster for small teams. Design first catches design mistakes while they're still cheap to fix. Either way, the spec lives in git and changes are reviewed like code.
OpenAPI paths name their parameters in braces, like /campaigns/{campaign_id}/ads/{ad_id}. Write path_params(path): return the names in order, without the braces.
def path_params(path): return [] print(path_params("/campaigns/{campaign_id}/ads/{ad_id}"))
A framework already knows every route. Turning that list into OpenAPI paths takes a few lines. Path parameters are found from the braces in the pattern.
import json, re routes = [ {"method": "GET", "path": "/campaigns", "operation_id": "list_campaigns", "summary": "List campaigns."}, {"method": "GET", "path": "/campaigns/{campaign_id}", "operation_id": "get_campaign", "summary": "Get one campaign."}, ] paths = {} for r in routes: path_params = re.findall(r"{(\w+)}", r["path"]) paths.setdefault(r["path"], {})[r["method"].lower()] = { "operationId": r["operation_id"], "summary": r["summary"], "parameters": [ {"name": p, "in": "path", "required": True, "schema": {"type": "string"}} for p in path_params ], } print(json.dumps(paths, indent=1)[:600])
Every route becomes an operation under its path, with the method in lowercase as OpenAPI expects. re.findall pulls the names out of {...} in the pattern. The exercise adds query parameters, request bodies and responses.
api.openapi() returns the whole spec as a dictionary. This reads one operation back out of it.
from fastapi import FastAPI api = FastAPI(title="Shop") @api.get("/campaigns/{campaign_id}", operation_id="get_campaign", summary="Get one campaign.") def get_campaign(campaign_id: str, verbose: bool = False): return {} spec = api.openapi() op = spec["paths"]["/campaigns/{campaign_id}"]["get"] print(op["operationId"], op["summary"]) print([(p["name"], p["in"], p["required"]) for p in op["parameters"]]) print(list(op["responses"])) print(spec["openapi"][:1], "<- the major version")
FastAPI took the operation id and summary you gave, found the path parameter from the braces and the query parameter from the function's signature, and added the 422 response for bad input. It is the same structure you generated by hand.
A tool definition for Claude has a name, a description and an input_schema. An OpenAPI operation has an operationId, a summary and parameter schemas. It's like copying a menu into another format: the dishes stay the same, and only the labels change. The match is almost one to one:
| OpenAPI | Claude tool |
|---|---|
operationId | name |
summary / description | description |
| parameters and request body schemas | input_schema.properties |
| required parameters | input_schema.required |
When the model calls the tool, your code turns its input back into a request: path parameters into the URL, query parameters into the query string, the body into JSON. This is how agents get access to a whole API at once, and how many MCP servers are generated.
Two cautions. First, descriptions written for developers aren't always good for models: a summary like "Get campaign" says nothing about when to use it. Second, don't expose every operation. An agent with a delete_all_campaigns tool will eventually use it. Pick a safe, useful subset.
An agent needs a name, a description and an input schema for each tool. A good spec already holds all three, so the conversion is a few lines.
import json spec = {"paths": {"/products/{id}": {"get": { "operationId": "getProduct", "summary": "Fetch one product by id", "parameters": [ {"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}, ], }}}} def to_tools(spec): tools = [] for path, methods in spec["paths"].items(): for method, op in methods.items(): params = op.get("parameters", []) tools.append({ "name": op["operationId"], "description": op["summary"], "input_schema": { "type": "object", "properties": {p["name"]: p["schema"] for p in params}, "required": [p["name"] for p in params if p.get("required")], }, }) return tools print(json.dumps(to_tools(spec)[0], indent=1))
The summary becomes what the model reads when it's choosing a tool. So a vague summary in your spec becomes a vague tool. Writing good specs now also helps every agent that uses your API later.
The reverse direction. A model's call is a name and an input. The spec says where each value goes: path values into the URL, query values into the query string, anything left into the body.
from urllib.parse import quote, urlencode SPEC = {"paths": {"/products/{id}": {"get": { "operationId": "getProduct", "parameters": [ {"name": "id", "in": "path", "required": True}, {"name": "fields", "in": "query"}, ], }}}} def to_request(spec, call): for path, methods in spec["paths"].items(): for method, op in methods.items(): if op["operationId"] != call["name"]: continue args, url, query = dict(call["input"]), path, {} for p in op.get("parameters", []): if p["in"] == "path": value = quote(str(args.pop(p["name"]))) url = url.replace("{" + p["name"] + "}", value) elif p["in"] == "query" and p["name"] in args: query[p["name"]] = args.pop(p["name"]) if query: url += "?" + urlencode(query) return method.upper(), url, args or None raise KeyError(call["name"]) call = {"name": "getProduct", "input": {"id": 7, "fields": "name,price"}} print(to_request(SPEC, call))
The id went into the path and fields into the query string, with the comma encoded. Nothing was left over, so the body is None. A real converter also checks each input against the tool's schema first, as Validating requests with schemas did.
op = {"operationId": "getItem", "summary": "Fetch one item"}
tool = {"name": op["operationId"], "description": op["summary"]}
print(tool["name"])getItem
tool["name"] holds op["operationId"], which is getItem. A good spec maps directly onto a tool definition.
Hundreds of tools crowd an agent's context and make it choose badly. Write pick_tools(tools, words, limit): score each tool by how many of words appear in its name or description (lowercase), keep tools scoring above 0, and return up to limit names, highest score first, ties in the original order.
TOOLS = [
{"name": "list_campaigns", "description": "List ad campaigns with their status."},
{"name": "get_invoice", "description": "Fetch one invoice by id."},
{"name": "pause_campaign", "description": "Pause a running ad campaign."},
{
"name": "campaign_stats",
"description": "Spend, clicks and return on ad spend for a campaign.",
},
{"name": "create_user", "description": "Invite a teammate."},
]
def pick_tools(tools, words, limit):
return [t["name"] for t in tools][:limit]
print(pick_tools(TOOLS, ["campaign", "spend"], 2))
Write a sentence or two, then compare it with a good answer in the lesson.
Generating tools from a spec is quick, and it's easy to overdo. Two problems come up every time.
Don't expose every operation. A new assistant doesn't need every key on the company's key ring. An API with 200 endpoints makes 200 tools. Tool definitions cost tokens on every call, and the model chooses worse from a long list. It may also pick something dangerous, like a delete, when all it needed was to look. Choose the few operations an agent needs, and combine several into one where that fits the task.
Rewrite descriptions for the model. "Retrieves the resource" is fine in docs for a developer, who can read around it. A model decides what to call from that text alone, so say when to use the tool, what comes back, and what it doesn't do.
Too many tools crowd the context and confuse the model, and dangerous operations become one call away
Every tool definition costs tokens and adds a choice. Expose a curated, safe subset, with descriptions that say when to use each tool.
The model decides what to call from that text alone
A developer can read around a thin description. A model can't, so say when to use the tool, what comes back and what it doesn't do.
A map is only useful if the roads still match it. Docs written by hand drift away from the real API, usually within weeks. So generate one from the other, or check them against each other in CI. If your code is the source, generate the spec from it. If the spec is the source, run tests that compare real responses against it.
A spec also lets a tool catch breaking changes automatically. Renaming a field, or making an optional one required, breaks clients that are already running. Tools such as oasdiff compare the old spec and the new one and fail the build, so you find out before your users do.
Two jobs recur. Generating a tool list from a spec, which takes an afternoon and then needs a week of pruning, since 200 tools make a worse agent than 12. And keeping a spec in step with the code, which means a check in CI, not a promise. The spec's openapi field names the version it follows, and newer minor versions exist, so check which version your tools expect. Goes deeper in: Build a server: tools serves tools like these over MCP, Capstone: a streaming chat service ends the phase with a service whose routes can be described this way, and CI/CD pipelines runs oasdiff in a pipeline.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
What is operationId used for?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write