FastAPI: From Basics to Production · FastAPI Basics
Automatic Docs and OpenAPI
Customize the generated OpenAPI schema, tags, examples and client generation.
FastAPI generates an OpenAPI 3.1 schema at /openapi.json and serves Swagger UI at /docs and ReDoc at /redoc. Improve it with tags, summaries, descriptions, response examples and documented error responses. The schema can generate typed clients (e.g., openapi-typescript, openapi-generator). Disable or protect docs in production if your API is private.
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict
app = FastAPI(
title="Bookstore API",
openapi_tags=[{"name": "books", "description": "Catalog operations"}],
docs_url="/docs", # set to None to disable in production
)
class Book(BaseModel):
model_config = ConfigDict(json_schema_extra={"examples": [{"id": 1, "title": "Dune", "price_cents": 1299}]})
id: int
title: str
price_cents: int
class ErrorOut(BaseModel):
detail: str
@app.get("/books/{book_id}", tags=["books"], summary="Get a book", responses={404: {"model": ErrorOut}})
async def get_book(book_id: int) -> Book: ...
Common pitfalls
- Undocumented error responses, so generated clients don't handle them.
- Exposing internal admin endpoints in public docs (use
include_in_schema=False). - Breaking the schema with untyped
dictreturns everywhere.
Key points
- /docs, /redoc and /openapi.json for free
- Document errors and examples
- Generate typed clients from the schema
Further reading: FastAPI: Metadata and docs URLs
Practice questions
How can a frontend benefit from FastAPI's OpenAPI schema?
Answer
Tools like openapi-typescript generate TypeScript types or clients from /openapi.json, keeping frontend types in sync with the API.
How do you hide an endpoint from the docs?
Answer
Pass include_in_schema=False to the route decorator (or router).
Open in the app to mark lessons complete, take notes and track your progress.