Home/Learn/FastAPI/Auto Docs — Swagger UI, ReDoc & OpenAPI

Auto Docs — Swagger UI, ReDoc & OpenAPI

Beginner
Fundamentals

Every FastAPI app ships /docs (Swagger UI), /redoc, and /openapi.json generated from your code — enrich them with tags, summaries, and examples, and lock them down in production.

Overview

FastAPI generates an OpenAPI specification from your routes, types, and models — the same information it uses for validation — and serves it three ways: /docs (interactive Swagger UI where requests can be executed), /redoc (clean reference reading), and /openapi.json (the raw spec other tools consume). Because docs derive from code, they cannot drift out of date — the eternal disease of hand-written API docs. You enrich them with tags to group endpoints, summary/description per route, and examples on models; the payoff is that frontend teammates test your API from a browser and client SDKs can be generated straight from the spec. In production, most teams disable or protect the docs URLs — internal API surfaces are reconnaissance gold.

Three URLs, Enriched from Code

Tags group endpoints into sections; summary and description explain each route; Field descriptions and json_schema_extra examples pre-fill the "Try it out" form. All of it lives next to the code it documents.

Docs written where they cannot rot: in the route and the model
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI(
    title="Campus Placement API",
    version="1.2.0",
    description="Drives the placement portal: students, drives, offers.",
)

class DriveIn(BaseModel):
    company: str = Field(description="Recruiting company", examples=["Infosys"])
    ctc_lpa: float = Field(ge=1, le=100, description="Package in LPA", examples=[6.5])
    min_cgpa: float = Field(default=6.0, ge=0, le=10)

    model_config = {
        "json_schema_extra": {
            "examples": [{"company": "TCS", "ctc_lpa": 7.0, "min_cgpa": 6.5}]
        }
    }

@app.post(
    "/drives",
    tags=["Drives"],                          # section heading in /docs
    summary="Create a placement drive",
    description="Registers a company drive. Students below min_cgpa will not see it.",
    response_description="The created drive",
)
def create_drive(drive: DriveIn):
    return drive

@app.get("/drives", tags=["Drives"], summary="List all drives")
def list_drives():
    return []

# http://127.0.0.1:8000/docs         Swagger UI — grouped, described, try-it-out
# http://127.0.0.1:8000/redoc        ReDoc — reference-style reading
# http://127.0.0.1:8000/openapi.json The spec — feed to generators/gateways

Docs as a Contract — and Locking Them Down

The OpenAPI JSON is machine-readable: generate typed frontend clients, import into Postman, diff between releases to catch breaking changes. In production, disable the URLs or hide them behind auth.

Generate clients from the spec; hide the spec in production
# 1. Generate a typed client from the running spec (frontend loves this):
npx openapi-typescript http://127.0.0.1:8000/openapi.json -o api-types.ts
# → TypeScript interfaces for every request/response model, always in sync

# 2. Deprecate before you delete:
@app.get("/v1/drives", deprecated=True, tags=["Drives"])
def old_list():                     # struck through in /docs, still functional
    return []

# 3. Production: docs off (or gated) —
import os
IS_PROD = os.getenv("ENV") == "prod"

app = FastAPI(
    docs_url=None if IS_PROD else "/docs",       # Swagger off in prod
    redoc_url=None,                              # ReDoc off everywhere
    openapi_url=None if IS_PROD else "/openapi.json",
)
# Why: /docs on a public service enumerates your entire attack surface —
# every route, parameter, and schema. Internal tools keep docs on;
# public APIs gate them behind auth or serve them only on the VPN.

# 4. Version discipline: bump app version on breaking changes;
#    CI can diff openapi.json between builds and fail on removals.

Key Points to Remember

  • 1/docs (interactive), /redoc (reading), /openapi.json (the machine spec)
  • 2Docs derive from code — they cannot drift out of date
  • 3tags group routes; summary/description/examples enrich the UI
  • 4Disable or gate docs URLs in production (docs_url=None)

Interview Questions

Sign in to ask Aria
1

How does FastAPI keep API docs in sync with code, unlike Swagger YAML by hand?

EasyPostman
2

What is OpenAPI and what can you build from an openapi.json?

MediumChargebee
3

Why disable /docs in production, and how would you keep it for internal engineers only?

MediumRazorpay

Ask Aria about Auto Docs — Swagger UI, ReDoc & OpenAPI

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…