Skip to content
Index Ai Academy
Phase 8 · Design at scale

Documenting APIs with OpenAPI

A machine-readable contract for docs, SDKs and AI tools.

About 40 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers10

First principles

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.

  1. Starting point

    The contract defines GET /reviews with a limit query parameter

  2. What changes

    A generator reads its name, type, and bounds

  3. Result

    The generated client exposes a typed limit argument

Compare all three steps
  1. Starting point

    The contract defines GET /reviews with a limit query parameter

  2. What changes

    A generator reads its name, type, and bounds

  3. Result

    The generated client exposes a typed limit argument

Complete and reverse the trace

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.

Compare with the worked step

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.

Check one starting point

The contract defines GET /reviews with a limit query parameter. Check that your implementation produces the result shown above.

Try it on a new case

If the server changes the successful response body from an array to an object, what should a contract check reveal?

Show worked reasoning

It should flag a schema mismatch. Clients built against the array may fail even when the status remains 200.

Try a different case

A response gains an optional field while all existing fields and types stay the same. What concrete test supports the compatibility claim?

Show reasoning for this case

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.

Run, change, and build

Check this when debugging. Hand-writing docs that drift away from the real API.

Trace the cause · HTTP request, job, and result
  1. Identify the request, response, and any durable state. Predict the status or stored result before following the trace.
  2. Change one request property and keep the client contract visible. Compare the response and job state to explain the observed behavior.
  3. Try the same reasoning on this case. If the server changes the successful response body from an array to an object, what should a contract check reveal?

Why it matters

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.

What you'll be able to do

  • Read an OpenAPI document: paths, operations, parameters, bodies and responses
  • Generate a spec from your routes, the way FastAPI does
  • Turn API operations into tool definitions an LLM agent can call
  • Use a spec for docs, generated SDKs, contract tests and spotting breaking changes
Quick check
Your API's documentation was written by hand last year. What's the most likely problem now?
  1. It's written in the wrong font
  2. Nothing: documentation never goes out of date
  3. It no longer matches what the code actually does
  4. It's too detailed for anyone to read
Show the answer

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.

The idea: one document, many tools

This rests on Validating requests with schemas: the schemas inside a spec are the JSON Schema you already read.

One document describes the whole API

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.

Quick check
From the lesson on validating requests: a schema lists the fields, their types, and which ones are required. What does this print for a body with no name?
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"]))
  1. ['name'] ['budget', 'name']
  2. ['name'] ['name']
  3. ['budget'] ['budget', 'name']
  4. [] ['budget', 'name']
Show the answer

['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.

Quick check
In OpenAPI, how does a parameter say it comes from the query string, like ?status=active?
  1. By starting its name with ?
  2. "in": "path"
  3. "in": "query"
  4. "location": "url"
Show the answer

"in": "query"

"in" can be path, query, header or cookie. Path parameters are always required.

What a spec gives you

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:

  • Interactive docs. Swagger UI and Redoc render the spec as browsable pages with "try it" buttons.
  • Client SDKs. Generators such as openapi-generator and Stainless write typed client libraries in many languages, with retries and pagination built in.
  • Validation. A server can check every request against the spec's schemas.
  • Mock servers. Front-end teams can build against fake responses before the API exists.
  • Contract tests. Tests check that real responses match the documented schemas.
  • Breaking-change checks. Comparing two versions of the spec in CI, the automatic checks that run on each change, flags a removed endpoint or a new required field before it ships. oasdiff is one tool for this.
  • AI tools. Each operation can become a tool for an LLM, as you'll build below.

In plain words: write one accurate description of your API, and let tools produce the rest from it.

Try it now

The words that make a good operation are the words a model reads when it picks a tool.

In your own words
What does an OpenAPI document describe, and which words of an operation become a tool's name and description?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: from routes to a spec, and from a spec to tools

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.

Code first or design first

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:

  • Code first: write the API, and generate the spec from it. FastAPI does this from your type hints and serves it at /openapi.json, with docs at /docs.
  • Design first: write the spec, review it with the people who'll call the API, then implement it and test against it.

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.

Drill

Find the path parameters

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}"))
In the lesson, your code is checked as you write it.
Worked example

Generating paths from a route table

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])
It runs right here in your browser, with nothing to install.

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.

Worked example

The spec FastAPI writes from a running app

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")
In the lesson you can change this and run it.

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.

From OpenAPI to LLM tools

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:

OpenAPIClaude tool
operationIdname
summary / descriptiondescription
parameters and request body schemasinput_schema.properties
required parametersinput_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.

Worked example

An operation becomes a tool

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))
In the lesson you can change this and run it.

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.

Worked example

A tool call back into a request

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))
In the lesson you can change this and run it.

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.

Quick check
What does this print?
op = {"operationId": "getItem", "summary": "Fetch one item"}
tool = {"name": op["operationId"], "description": op["summary"]}
print(tool["name"])
  1. Fetch one item
  2. name
  3. operationId
  4. getItem
Show the answer

getItem

tool["name"] holds op["operationId"], which is getItem. A good spec maps directly onto a tool definition.

Drill

Give the agent only the tools it needs

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))
In the lesson, your code is checked as you write it.
In your own words
How does a route table become a spec, and a spec become a tool list?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML systems: a spec for people is not a spec for a model

Choose the tools, and rewrite the words

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.

Quick check
You convert a 300-operation OpenAPI spec into 300 tools for an agent. What's the main risk?
  1. The API gets much faster, since the agent calls each operation directly
  2. Too many tools crowd the context and confuse the model, and dangerous operations become one call away
  3. Claude can't read JSON Schema, so the tools' inputs would be ignored when it calls them
  4. Nothing: more tools always help, since the agent has more ways to finish a task
Show the answer

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.

Quick check
Why rewrite an operation's description for a model?
  1. Models can't read more than a few words
  2. Developers have stopped reading the docs
  3. The model decides what to call from that text alone
  4. A shorter description makes the tool faster
Show the answer

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.

Keep the spec honest

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.

Where this shows up in an engineer's week

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.

In your own words
What is the risk of turning every operation into a tool, and what do you change in the words?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 4 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 8 review cards for spaced repetition

Try a quiz question

What is operationId used for?

  1. A unique name for an operation, used for generated method names and tool names
  2. The HTTP status code that the operation returns when a call succeeds
  3. The database table name that the operation reads from and writes to
  4. The API key that a client has to send in order to call the operation

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 8 · about 23 hours of study

APIs

Design, build, secure and scale web APIs from first principles 27 lessons 1 free
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
  22. A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
  27. Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Part of a free course 127 lessons

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.

Part of a free course 20 lessons

Build and Operate HTTP APIs

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