In API development, automatically generated interactive documentation is an essential tool. It helps developers and users quickly understand an interface’s functionality, parameters, and return values, and even allows direct interface testing in a browser. The FastAPI framework comes with powerful built-in documentation generation capabilities based on Swagger UI and OpenAPI specifications, making documentation simple and efficient.
Why is automatic documentation necessary?¶
Imagine if your API had no documentation—developers would need to manually consult the code to know how to call the interface; if parameters are complex, users might report errors due to unclear formats. FastAPI’s automatic documentation not only clearly displays the interface structure but also supports interactive testing, significantly reducing the threshold for API usage.
What is the relationship between Swagger UI and OpenAPI?¶
- OpenAPI: A specification that defines API structure and interaction methods, describing interface paths, parameters, responses, etc., in JSON format. The documentation generated by FastAPI is essentially an OpenAPI-compliant JSON file.
- Swagger UI: An interactive documentation tool based on the OpenAPI specification. It parses FastAPI-generated OpenAPI JSON files to visualize API documentation and provides a “Try it out” feature for direct interface testing.
- ReDoc: Another OpenAPI-based documentation tool similar to Swagger UI but with a cleaner interface, suitable for scenarios requiring more structured documentation. FastAPI also supports it; access it via
/redoc.
How to enable documentation in FastAPI?¶
Creating a simple FastAPI application will automatically generate documentation upon running. Here’s an example:
from fastapi import FastAPI
# Create an app instance, with parameters to set basic documentation information
app = FastAPI(
title="FastAPI Example",
description="This is a demo using FastAPI to auto-generate documentation",
version="1.0.0"
)
@app.get("/")
def read_root():
return {"message": "Hello World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
Run the app with:
uvicorn main:app --reload
Then access:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
You’ll see the auto-generated documentation, including title, description, interface list, and parameter explanations.
Practical Tips: Making Documentation Clearer and More Usable¶
1. Customize Basic Documentation Information¶
Set global documentation information via FastAPI constructor parameters:
app = FastAPI(
title="E-commerce API", # Documentation title
description="API for managing products and orders, supporting user queries and order placement",
version="1.0.0", # Version number
terms_of_service="https://example.com/terms", # Terms of service link
contact={"name": "Development Team", "email": "dev@example.com"} # Contact information
)
2. Detailed Interface and Parameter Descriptions¶
Add interface and parameter descriptions through three methods:
- Function Docstring: Directly write comments in the function; FastAPI automatically parses them into the documentation.
- Parameter Decorators: Use tools like Path and Query to add parameter descriptions.
- Interface Decorators: Use parameters like description, summary, and tags.
Example:
from fastapi import Path, Query
@app.get("/items/{item_id}",
tags=["Product Queries"], # Categorize by tags for easy filtering
summary="Query Product Details", # Brief interface description
description="Query detailed information by product ID<br/>- **item_id** must be an integer<br/>- Supports returning product stock status")
def read_item(
item_id: int = Path(...,
title="Product ID",
description="Unique identifier (1-1000)",
ge=1, le=1000), # ge=1 means greater than or equal to 1
q: str = Query(None,
title="Search Keyword",
description="Optional, for fuzzy matching product names")
):
return {"item_id": item_id, "q": q}
3. Hide Internal/Unpublic Interfaces¶
To hide interfaces used only internally (e.g., debug interfaces), use include_in_schema=False:
@app.get("/internal/debug", include_in_schema=False) # Hide this interface
def internal_debug():
return {"debug": "This is internal only"}
4. Standardize Return Format with Response Models¶
Define interface return data using Pydantic models; documentation automatically generates examples and parameter structures:
from pydantic import BaseModel
class ItemResponse(BaseModel):
name: str
price: float
stock: int = 0 # Default value
@app.get("/items/{item_id}", response_model=ItemResponse)
def read_item(item_id: int):
return {"name": "Mobile Phone", "price": 2999.99, "stock": 100}
5. Display Error Information¶
Define possible error status codes using HTTPException; documentation automatically annotates them:
from fastapi import HTTPException
@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id > 100:
raise HTTPException(
status_code=400,
detail="Product ID cannot exceed 100"
)
return {"item_id": item_id}
Summary¶
FastAPI’s automatic documentation is based on the OpenAPI specification and provides intuitive interface display via Swagger UI and ReDoc. Key points for effective documentation:
- Set global information (title, description, etc.) via FastAPI constructor parameters.
- Use function comments, Path/Query, etc., to detail interfaces and parameters.
- Categorize interfaces with tags for easy filtering.
- Hide internal interfaces to avoid documentation clutter.
- Use Pydantic models to standardize return formats and auto-generate examples.
Automatically generated documentation saves manual writing time, ensures interface information aligns with code, and improves team collaboration and user experience.
With these techniques, even beginners can quickly master FastAPI documentation generation, making your API more professional and user-friendly!