FastAPI automatically generates interactive API documetnation at /docs and /redoc endpoints, but refining these docs improves clarity for frontend developers and acts as backend注释. Here’s how to enhance and manage them.
Global Documentation Settings
Customize overall doc metadata when initializing FastAPI:
from fastapi import FastAPI
app = FastAPI(
title="Project API Documentation",
description="Comprehensive API endpoints for managing content and user interactions",
version="2.1.3"
)
Path Operation Descriptions
Add clear titles and descriptions to endpoints:
@app.get("/content-list", summary="Fetch Content List", description="Retrieve paginated content items without any required input parameters")
def fetch_content_list():
return {"data": []}
Path Parameter Details
Define constraints and explanations for path variables using Path:
from fastapi import Path
@app.get("/content-details/{item_id}", summary="Get Content Details", description="Fetch detailed information about a specific content item by ID")
def fetch_content_details(
item_id: int = Path(..., description="Unique identifier for content item, minimum value is 10")
):
return {"data": {"id": item_id}}
Query Parameter Documentation
Document URL query parameters with Query:
from fastapi import Query
@app.get("/search-content", summary="Search Content", description="Search and filter content items with query strings and pagination")
def search_content(
page: int = Query(1, description="Page number for paginated results, defaults to 1"),
keyword: str = Query(None, description="Keyword to search in content titles and descriptions")
):
return {"data": {"page": page, "keyword": keyword}}
Request Body Structure
Define request body schemas with Pydantic models and Field:
from pydantic import BaseModel, Field
class LoginPayload(BaseModel):
email: str = Field(..., description="User's registered email address")
password: str = Field(..., description="User's login password")
@app.post("/user-login")
async def user_login(payload: LoginPayload):
return {"message": "Login successful"}
Response Body Definition
Specify response data structures using response_model and Pydantic:
class ContentResponse(BaseModel):
title: str = Field(..., description="Content item title")
published_date: str = Field(..., description="Date when content was published")
@app.get("/featured-content/{item_id}", response_model=ContentResponse)
async def get_featured_content(item_id: int):
return {
"title": "Introduction to FastAPI",
"published_date": "2024-01-15"
}
Detailed Notes with Docstrings
Add additional context using endpoint docstrings:
@app.get("/welcome")
def welcome_message():
"""
Send a friendly welcome message
- Returns a JSON object with a single "greeting" key
- The value is localized based on request headers (if configured)
"""
return {"greeting": "Hello!"}
Dsiabling Documentation
Turn off documentation endpoints for production:
app = FastAPI(
openapi_url=None # Disables both /docs and /redoc by removing OpenAPI schema
)