पाठ 7 / 26

Automatic OpenAPI Documentation

Docs generated from code.

/docs, /openapi.json and clients

FastAPI builds an OpenAPI specification from your routes, parameter types and models: it is served at /openapi.json, with interactive Swagger UI at /docs and ReDoc at /redoc. Summaries, descriptions, tags and examples improve it. Because the spec matches the code, client SDKs can be generated from it and contract tests can check it. Validation error responses (422) are documented automatically.

Inspecting the generated specification, run

I ran this with Python 3.12, FastAPI 0.142.2, Pydantic 2.13 and Starlette 1.7, calling the app through FastAPI's TestClient (no server needed). The spec uses OpenAPI 3.1, lists each route with its responses (including the automatic 422) and the schemas for the Item model and validation errors.

from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

app = FastAPI(title="Shop API", version="1.0.0")

@app.get("/items/{item_id}", summary="Get one item")
def read(item_id: int) -> Item:
    return Item(name="Pen", price=899)

@app.post("/items", status_code=201)
def create(item: Item) -> Item:
    return item

spec = app.openapi()          # the same document served at /openapi.json and /docs
print(spec["info"]["title"], spec["info"]["version"], spec["openapi"][:3])
for path, ops in spec["paths"].items():
    for method, op in ops.items():
        print(method.upper(), path, "-", op.get("summary"), "-", sorted(op["responses"]))
print("schemas:", sorted(spec["components"]["schemas"]))

Output:

Shop API 1.0.0 3.1
GET /items/{item_id} - Get one item - ['200', '422']
POST /items - Create - ['201', '422']
schemas: ['HTTPValidationError', 'Item', 'ValidationError']

Commit the spec in CI

Export openapi.json in CI and diff it in pull requests to catch accidental breaking API changes.

त्वरित जाँच: Where does FastAPI serve interactive API documentation by default?

  • /docs
  • /admin
  • /swagger.php
  • Nowhere
Answer

/docs — Swagger UI at /docs, spec at /openapi.json.