> ## Documentation Index
> Fetch the complete documentation index at: https://fastapi2day.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# API Documentation: Swagger UI and ReDoc in FastAPI

> Customise FastAPI's auto-generated OpenAPI documentation with app metadata, route summaries, field descriptions, and interactive Swagger UI testing.

One of FastAPI's most loved features is its **automatic, interactive API documentation**. The moment your application starts, FastAPI reads your Python type hints, Pydantic schemas, and docstrings, generates a standard **OpenAPI specification**, and hosts two interactive web portals where clients — and you — can explore and test every endpoint live. No extra tooling, no manual YAML files, no separate documentation project to maintain. This lesson shows you how to get the most out of it.

***

## Documentation Generation Architecture

FastAPI acts like a compiler that translates Python code annotations directly into standardised documentation layers:

```mermaid theme={null}
graph TD
    Code["FastAPI Code (Type Hints, Pydantic, Docstrings)"] --> Compile[FastAPI Engine]
    Compile --> Spec["OpenAPI Specification (openapi.json)"]

    Spec --> Swagger["Swagger UI (/docs)\nInteractive testing playground"]
    Spec --> ReDoc["ReDoc (/redoc)\nClean, deep-nested documentation"]
```

***

## The Two Built-In Portals

When your FastAPI application is running (e.g., at `http://127.0.0.1:8000`), you automatically get access to two documentation UIs:

<Tabs>
  <Tab title="Swagger UI (/docs)">
    **URL:** `http://127.0.0.1:8000/docs`

    Swagger UI is the primary developer playground. You can:

    * View the full schema of every request and response model
    * Expand each endpoint to inspect its parameters
    * Click **"Try it out"** to send real HTTP requests directly from the browser
    * Inspect the actual response body, status code, and headers

    Swagger UI is the fastest way to test your API during development — no Postman or curl required.
  </Tab>

  <Tab title="ReDoc (/redoc)">
    **URL:** `http://127.0.0.1:8000/redoc`

    ReDoc provides a highly structured, clean layout optimised for documentation readers. It's ideal for:

    * Sharing with external consumers or stakeholders
    * Navigating large APIs with many endpoints
    * Reading detailed schemas without executing requests

    ReDoc does not support live request execution.
  </Tab>

  <Tab title="OpenAPI JSON">
    **URL:** `http://127.0.0.1:8000/openapi.json`

    The raw OpenAPI 3.x specification as JSON. You can import this into Postman, Insomnia, or any OpenAPI-compatible tool.
  </Tab>
</Tabs>

***

## App-Level Metadata

Customise the global documentation by passing metadata to the `FastAPI()` constructor:

```python theme={null}
from fastapi import FastAPI

app = FastAPI(
    title="🏢 Employee Management System (EMS) API",
    description="""
    Welcome to the enterprise **Employee Management System** portal.

    This API allows you to:
    * **Manage Employee Directories** — Create, read, update, and delete employee profiles.
    * **Department Structuring** — Organise teams and roles.
    * **Real-time Communication** — Send peer-to-peer and group messages.
    """,
    version="1.0.0",
    contact={
        "name": "EMS Support Team",
        "email": "support@company.com"
    }
)
```

The `description` field supports **Markdown** — use it to write rich documentation with headings, bullet lists, bold text, and links.

***

## Route-Level Metadata

Add documentation to individual endpoints using parameters on the path operation decorator:

```python theme={null}
from fastapi import APIRouter, status

router = APIRouter()

@router.post(
    "/employees",
    status_code=status.HTTP_201_CREATED,
    summary="Onboard a new employee",
    description="""
    Registers a new employee in the database, creates their default profile,
    and sends an alert to the HR system.

    **Required fields:** `name`, `department`, `role`
    """,
    response_description="The newly created employee profile including their assigned database ID"
)
def create_employee():
    return {"message": "Success"}
```

| Parameter              | Purpose                                                       |
| ---------------------- | ------------------------------------------------------------- |
| `summary`              | Short one-line title shown in the endpoint list               |
| `description`          | Full Markdown description shown when the endpoint is expanded |
| `response_description` | Explains what the returned payload represents                 |

<Tip>
  You can also use a Python **docstring** on the function as the description — FastAPI reads it automatically:

  ```python theme={null}
  @app.get("/employees")
  def list_employees():
      """
      Retrieve a paginated list of all employees.

      Supports filtering by department and sorting by name.
      """
      ...
  ```
</Tip>

***

## Parameter and Field Descriptions

Add descriptions to individual Pydantic fields and query parameters to make the Swagger UI self-explanatory:

```python theme={null}
from pydantic import BaseModel, Field
from fastapi import Query

class EmployeeCreate(BaseModel):
    name: str = Field(
        ...,
        min_length=2,
        description="The employee's first and last name.",
        examples=["Jane Doe"]
    )
    salary: float = Field(
        ...,
        gt=0,
        description="Monthly gross salary in USD.",
        examples=[7500.0]
    )

@app.get("/employees")
def list_employees(
    limit: int = Query(
        10,
        description="Maximum number of employee records to return.",
        ge=1,
        le=100
    ),
    department: str | None = Query(
        None,
        description="Filter employees by department name."
    )
):
    return []
```

All descriptions are parsed and rendered directly in Swagger UI and ReDoc — keeping your documentation always in sync with your code.

***

## Tagging Endpoints

Use `tags` to group related endpoints together in the Swagger UI sidebar:

```python theme={null}
from fastapi import APIRouter

employees_router = APIRouter(prefix="/employees", tags=["Employees"])
departments_router = APIRouter(prefix="/departments", tags=["Departments"])
auth_router = APIRouter(prefix="/auth", tags=["Authentication"])
```

You can also add tags directly on individual route decorators:

```python theme={null}
@app.get("/employees", tags=["Employees"])
def list_employees():
    ...
```

***

## Deprecating Endpoints

Mark an endpoint as deprecated without removing it — useful during API version transitions:

```python theme={null}
@app.get("/employees/all", deprecated=True)
def list_all_employees_legacy():
    """Use GET /employees instead."""
    return []
```

Deprecated endpoints are shown with a strikethrough in Swagger UI and are clearly marked in ReDoc.

***

## Complete Documentation Example

Here is a fully documented endpoint combining app metadata, route metadata, field descriptions, and tags:

```python theme={null}
from fastapi import FastAPI, status
from pydantic import BaseModel, Field

app = FastAPI(
    title="Employee Management System API",
    description="Manage employees, departments, and roles.",
    version="2.0.0",
    contact={"name": "API Support", "email": "api@company.com"}
)

class EmployeeCreate(BaseModel):
    name: str = Field(..., min_length=2, description="Full name of the employee.", examples=["Alice Smith"])
    department: str = Field(..., description="Assigned department.", examples=["Engineering"])
    role: str = Field(..., description="Job title or role.", examples=["Backend Developer"])

class EmployeeOut(EmployeeCreate):
    id: int = Field(..., description="Auto-assigned employee ID.")

@app.post(
    "/employees",
    response_model=EmployeeOut,
    status_code=status.HTTP_201_CREATED,
    summary="Onboard a new employee",
    description="Creates a new employee record and returns the assigned ID.",
    response_description="The newly created employee with their assigned ID.",
    tags=["Employees"]
)
def create_employee(employee: EmployeeCreate):
    return {"id": 101, **employee.model_dump()}
```

<Note>
  The documentation you write here stays automatically in sync with your code. If you rename a field, change a type, or add a new parameter, the Swagger UI and ReDoc pages update the next time the server reloads — no manual documentation maintenance required.
</Note>
