Skip to content

By the Octri team · Updated

FastAPI documentation: Swagger UI, ReDoc and hosting

Share

FastAPI documentation comes from your code. Every route you write shows up in Swagger UI at /docs, in ReDoc at /redoc and in the OpenAPI spec at /openapi.json, and this guide covers what FastAPI can't work out alone.

How do you document a FastAPI API?

You document a FastAPI API by writing more careful Python. FastAPI reads your type hints, your Pydantic models, your docstrings and a handful of keyword arguments, and turns them into an OpenAPI spec. Swagger UI and ReDoc are two different readers of that one file.

Most of the work happens in three places. The FastAPI() call holds the metadata for the whole API, each route decorator holds what's specific to one endpoint, and the Pydantic models hold the fields with their descriptions and examples. Get those right and both docs pages get better at once, and so does every tool that reads the spec, SDK generators included.

I built a small invoices API with FastAPI 0.165.0 and Pydantic 2.14 for this guide, and every snippet and every output below comes from it. The first version looked finished in /docs. It had a title, docstrings, examples and an Authorize button. Then I tested it against its own spec and found two things the page didn't show. A request without an API key came back 401, and the spec didn't list a 401 anywhere. And with the docs pages switched off for production, /openapi.json was still public. Generating an SDK with FastAPI's default operation IDs turned up a third, a method called create_invoices_post. The sections below fix all three.

Where /docs, /redoc and /openapi.json come from

Think of the spec as sheet music. /openapi.json is the score, and Swagger UI and ReDoc are two musicians playing it. They play it differently, Swagger UI with a "Try it out" button on every endpoint and ReDoc as a three-column reference you read, but neither one adds a note that isn't in the score.

FastAPI builds the score from your app the first time someone asks for it. On the version I tested, it starts with "openapi": "3.1.0" (see what is an OpenAPI spec? for what that line means), and both docs pages load it from your server in the browser.

Rule of thumb: when something looks wrong in /docs, fix the Python that produced the spec. There's nothing to edit in Swagger UI itself, and a fix in the spec reaches every other tool that reads it too.

Fill in the API's metadata

The FastAPI() call sets the title, version and description at the top of both docs pages, and it's where the servers and the tag descriptions go.

python
tags = [
    {"name": "invoices", "description": "Create invoices and look them up."},
]

app = FastAPI(
    title="Acme Billing API",
    version="1.4.0",
    summary="Invoices and payments for Acme customers.",
    description="Every request needs an API key in the `X-API-Key` header.",
    openapi_tags=tags,
    servers=[{"url": "https://api.acme.example", "description": "Production"}],
)

The description is Markdown, so the header name renders as code. The tag description shows up next to the invoices group in Swagger UI, and without servers the docs send "Try it out" requests to whatever host served the page. FastAPI's metadata and docs URLs page lists every field.

Describe each endpoint

FastAPI reads more from a route than most people expect. The function name becomes the summary, the docstring becomes the description, and the tags decide which group the endpoint sits in.

python
@app.post(
    "/invoices",
    tags=["invoices"],
    status_code=201,
    response_model=Invoice,
)
def create_invoice(invoice: InvoiceIn, key: str = Security(api_key)):
    """Create an invoice for a customer.

    The invoice starts as `open`. Amounts are in the smallest currency unit.
    """

In the spec, that endpoint got the summary Create Invoice and the docstring as its description. Watch the function names, though. A route named list_invoices_v1 got the summary List Invoices V1, which is accurate and reads badly as a title. Pass summary= when the function name doesn't read well as a title.

deprecated=True marks a route as deprecated in the spec, and Swagger UI strikes it through. That's the cheapest warning you'll ever give your users.

Give every operation a clean operationId

This is the setting that matters most once anything other than a person reads your docs. Every operation in an OpenAPI spec has an operationId, and SDK generators use it to name the method a developer calls.

FastAPI's default joins the function name, the path and the method. My two routes came out as create_invoice_invoices_post and get_invoice_invoices__invoice_id__get. Here's what Octri's SDK generator did with each, for the same endpoint:

operationId in the spec Python SDK call TypeScript SDK call
create_invoice_invoices_post (FastAPI default) client.invoices.create_invoices_post(...) client.invoices.createInvoicesPost(...)
create_invoice (custom function below) client.invoices.create(...) client.invoices.create(...)

FastAPI lets you replace the default with one function, which it documents in generating clients:

python
from fastapi.routing import APIRoute


def operation_id(route: APIRoute) -> str:
    return route.name


app = FastAPI(generate_unique_id_function=operation_id)

Each operationId has to be unique across the whole API. If two routers both have a function called get, put the tag in front of the name, the way FastAPI's own example does.

Rule of thumb: name each route function the way you'd want the SDK method to read.

Add examples

Examples are where a reader learns what the API looks like without reading every field description. FastAPI takes them in two places.

On a Pydantic model, Field(examples=[...]) puts an example on each field, and Swagger UI assembles them into a whole example request and response:

python
class InvoiceIn(BaseModel):
    customer_id: str = Field(description="The customer to bill.",
                             examples=["cus_123"])
    amount: int = Field(gt=0, description="Amount in cents.",
                        examples=[4999])
    currency: str = Field(default="usd",
                          description="Three-letter ISO currency code.")

On a request body, Body(openapi_examples={...}) gives Swagger UI a dropdown of named examples. Each one has a summary and a value:

python
invoice: InvoiceIn = Body(
    openapi_examples={
        "small": {
            "summary": "A small invoice",
            "value": {"customer_id": "cus_123", "amount": 4999},
        },
        "euro": {
            "summary": "Billed in euros",
            "value": {"customer_id": "cus_123", "amount": 12000,
                      "currency": "eur"},
        },
    }
)

The gt=0 on amount shows up in the spec too, as exclusiveMinimum, so validation rules become documentation for free. FastAPI's page on declaring request examples covers the differences between the two kinds.

Swagger UI for the sample FastAPI app, with POST /invoices expanded to show its docstring description, the "A small invoice" example in a dropdown, and a 201 response example built from the field examples.
The sample app's Swagger UI. The docstring became the description, the named examples became a dropdown, and the response example was built from the Field examples.

Document the errors

FastAPI documents some errors on its own and leaves others out, and the gap isn't obvious until you compare the spec with what the API returns. I sent requests to the sample app and checked each status against its spec:

Status When the sample API returns it In the generated spec?
201 Invoice created Yes
401 No X-API-Key header No
404 GET /invoices/{invoice_id} with an unknown ID Only after adding it
422 amount of 0, or another invalid field Yes, on the two routes that take input

The 422 comes free, because FastAPI adds it to any operation with parameters or a body. The 401 comes from the API key dependency, and nothing tells the spec about it. Readers find out when their first request fails.

Declare the errors with responses, which takes a status code and a model for the error body. Put the ones every operation shares on FastAPI() itself, and the endpoint-specific ones on the route:

python
class Error(BaseModel):
    detail: str = Field(examples=["Invoice not found"])


app = FastAPI(
    responses={401: {"model": Error,
                     "description": "The API key is missing or wrong."}},
)


@app.get(
    "/invoices/{invoice_id}",
    response_model=Invoice,
    responses={404: {"model": Error,
                     "description": "No invoice has this ID."}},
)
def get_invoice(invoice_id: str, key: str = Security(api_key)) -> Invoice:
    ...

In my test, the app-wide 401 showed up on the route next to FastAPI's own 422, and the route's 404 sat beside them. FastAPI's additional responses page has the other options.

Document authentication

FastAPI's security classes add themselves to the spec. An APIKeyHeader dependency becomes an apiKey security scheme, every route that uses it gets a security entry, and Swagger UI shows an Authorize button where readers paste their key.

The scheme's name in the spec is the class name, APIKeyHeader, unless you give it one. That name shows up in SDKs and docs, so give it a real one:

python
api_key = APIKeyHeader(
    name="X-API-Key",
    scheme_name="ApiKey",
    description="Your secret API key.",
)

How to document API authentication covers the parts a spec can't hold, like where a developer gets the key and what each scope allows.

Configure Swagger UI

swagger_ui_parameters passes settings straight through to Swagger UI. The one I'd set on most APIs hides the list of every schema at the bottom of the page, which repeats what each endpoint already shows:

python
app = FastAPI(swagger_ui_parameters={"defaultModelsExpandDepth": -1})

FastAPI's Swagger UI configuration page has the rest, from turning off syntax highlighting to changing its theme.

Decide what production serves

You can turn the docs pages off with docs_url=None and redoc_url=None, and a lot of teams do that in production. Test what's left, though. In the sample app with both set to None, /docs and /redoc returned 404 and /openapi.json still returned 200.

The spec itself goes away only with openapi_url=None, which also turns off both pages. FastAPI's conditional OpenAPI page shows how to drive that from an environment variable.

Which one you want depends on who the API is for. For a public API, keep the spec public. It's how docs platforms, SDK generators and AI tools import your API, and hiding it doesn't hide the endpoints. For an internal API, turn it off and export the spec in CI.

Export the spec in CI

app.openapi() builds the same document /openapi.json serves, and it doesn't need a running server. A short script writes it to a file:

python
import json

from main import app

with open("openapi.json", "w") as f:
    json.dump(app.openapi(), f, indent=2)

Run it in CI on every merge and commit the file, or send it wherever your docs are built. Here's a tip: commit openapi.json and review its diff in pull requests. A renamed function, a lost docstring or a changed field shows up there before your users see it.

Host the docs

Swagger UI is a request console for one spec, and it's great for development. A docs site that developers outside your team use needs more around it: guides for real tasks, search, code samples in their language, a changelog, and a sign-in or a password when the API isn't public. Swagger UI vs hosted API docs compares the two, and what is an API developer portal covers the rest of what a portal holds.

The exported spec is the input for all of it. A hosted docs site built from the same openapi.json keeps the reference in step with the code, and you write the guides around it.

Unofficial Clerk API showcase built with Octri, showing the Create a new user reference page with its request body fields, a TypeScript SDK sample calling client.users.create(), response codes and a Try it button.
An unofficial Clerk API showcase built with Octri. The reference page comes from the spec, and the SDK sample calls client.users.create(), named from the operation.
Unofficial Clerk API showcase built with Octri, with the Try it drawer open on Retrieve a user, bearer token authentication selected and a user_id path parameter.
The same showcase with its Try it drawer open. The authentication type and the path parameter come from the spec.

FastAPI documentation best practices

  • Fix the spec, never the page. Both docs pages render /openapi.json, so every fix belongs in the Python that produces it.
  • Name functions like SDK methods. Set generate_unique_id_function so each operationId reads like the method a developer will call.
  • Write a docstring for every route. It becomes the description in both docs pages and in anything built from the spec.
  • Give every field a description and an example. Field(description=..., examples=[...]) costs one line per field.
  • Declare the errors your dependencies raise. FastAPI adds 422 on its own. Add 401, 403 and 404 with responses.
  • Name the security scheme. scheme_name keeps a class name out of your docs.
  • Set servers. "Try it out" then calls the API, wherever the docs are hosted.
  • Decide what production serves. docs_url=None leaves /openapi.json public. openapi_url=None turns all three off.
  • Export and diff the spec in CI. A committed openapi.json makes every docs change reviewable.

FastAPI documentation checklist

  • Title, version, summary and description set on FastAPI().
  • Tag descriptions in openapi_tags, and a servers entry.
  • A docstring on every route, and summary= where the function name reads badly.
  • Clean, unique operation IDs from generate_unique_id_function.
  • Descriptions and examples on every model field, and named examples on request bodies.
  • Error responses declared with responses, including the ones dependencies raise.
  • A named security scheme.
  • Deprecated routes marked with deprecated=True.
  • A clear decision on docs_url, redoc_url and openapi_url in production.
  • openapi.json exported in CI and reviewed in pull requests.
  • Hosted docs built from the exported spec, with guides around the reference.

FastAPI documentation with Octri

Octri API Studio turns your FastAPI spec into a hosted docs site, and there are three ways to get it there. Point Octri at your app's /openapi.json and it checks the URL once a day on the Growth plan and up, or connect the repository where CI commits openapi.json and it syncs on every push. You can also run npx @octri/cli specs push openapi.json as a CI step with OCTRI_API_KEY and OCTRI_PROJECT_ID set. New versions can go live on their own or wait as a draft, and the edits you make to an endpoint page in Octri survive the next spec.

The docs get the reference, guides, search and a playground on each endpoint, and custom domains are on every plan, Free too. The same spec builds SDKs in ten languages, whose method names come from those operation IDs, and a hosted MCP server for AI agents. If you want to see the API's errors and latency as well, pip install octri and add app.add_middleware(OctriMiddleware) from octri.fastapi to the app.

Share

Keep reading