FastAPI 交互式 API 文档
FastAPI 交互式 API 文档:Swagger UI & ReDoc 完全指南
FastAPI 的 最大亮点之一 就是 自动生成交互式 API 文档,无需手写!
它基于 OpenAPI(原 Swagger)标准,开箱即用。
一、FastAPI 自动生成的两大文档
| 文档类型 | 地址 | 特点 |
|---|---|---|
| Swagger UI | /docs | 交互式、支持直接测试、适合开发调试 |
| ReDoc | /redoc | 更美观、适合文档展示、响应式设计 |
二、默认启用文档(无需配置)
from fastapi import FastAPI
app = FastAPI() # 自动启用 /docs 和 /redoc
@app.get("/")
def home():
return {"message": "Hello FastAPI!"}
运行后访问:
- Swagger UI(交互式):http://127.0.0.1:8000/docs
- ReDoc(文档式):http://127.0.0.1:8000/redoc
- OpenAPI JSON:http://127.0.0.1:8000/openapi.json
三、Swagger UI 交互式功能演示
打开 http://127.0.0.1:8000/docs,你会看到:
graph TD
A[Swagger UI 页面] --> B[API 列表]
B --> C[端点分组]
C --> D[参数输入框]
D --> E[Try it out 按钮]
E --> F[发送请求]
F --> G[实时响应]
G --> H[复制 cURL]
核心操作(不用写一行测试代码):
| 操作 | 说明 |
|---|---|
| Try it out | 点击后可编辑参数 |
| 输入参数 | 支持路径、查询、请求体 |
| Execute | 发送真实请求 |
| Response | 实时显示响应体、状态码、Headers |
| cURL | 一键复制 cURL 命令 |
| Schema | 查看 Pydantic 模型结构 |
四、自定义文档信息(推荐!)
app = FastAPI(
title="用户管理系统 API", # 文档标题
version="1.0.0", # 版本号
description="""
一个完整的用户 CRUD 系统,演示 FastAPI 最佳实践。
## 功能
- 用户注册
- 用户查询
- 数据验证
- 错误处理
""",
contact={
"name": "API 支持",
"url": "https://example.com/support",
"email": "support@example.com"
},
license_info={
"name": "MIT",
"url": "https://opensource.org/licenses/MIT"
}
)
效果:
- 标题、版本、描述会显示在文档顶部
- 支持 Markdown 语法
五、使用 tags 分组端点(强烈推荐)
@app.get("/users/", tags=["用户管理"])
def get_users():
...
@app.post("/users/", tags=["用户管理"])
def create_user():
...
@app.get("/health", tags=["系统监控"])
def health_check():
...
效果:在 Swagger UI 中自动分组:
用户管理
├── GET /users/
├── POST /users/
└── ...
系统监控
└── GET /health
六、为端点添加详细说明(支持 Markdown)
@app.post("/users/", tags=["用户管理"], summary="创建新用户", description="""
### 业务规则
- 用户名必须唯一
- 邮箱格式必须合法
- 年龄必须在 1-120 之间
### 示例请求
json
{
“username”: “alice”,
“email”: “alice@example.com”,
“age”: 25
}
""")
def create_user(user: UserCreate):
...
七、隐藏或禁用文档(生产环境可选)
# 完全禁用文档
app = FastAPI(docs_url=None, redoc_url=None)
# 仅禁用 Swagger UI
app = FastAPI(docs_url=None, redoc_url="/redoc")
# 自定义路径
app = FastAPI(docs_url="/api/docs", redoc_url="/api/redoc")
生产环境建议:保留 ReDoc,禁用 Swagger UI 的
Try it out功能(防止误操作)
八、为请求体添加示例(在文档中显示)
from pydantic import BaseModel
class UserCreate(BaseModel):
username: str
email: str
age: int
model_config = {
"json_schema_extra": {
"examples": [
{
"username": "alice",
"email": "alice@example.com",
"age": 25,
"bio": "Python 开发者"
}
]
}
}
效果:在 Swagger UI 中自动显示 Example Value
九、下载 OpenAPI 规范(用于前端、Postman)
curl http://127.0.0.1:8000/openapi.json > openapi.json
用途:
- 生成 TypeScript 类型(
openapi-typescript) - 导入 Postman
- 生成 SDK(
openapi-generator)
十、完整示例:带文档的项目
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStr
from typing import Optional
app = FastAPI(
title="用户管理 API",
version="1.0.0",
description="一个带完整交互文档的 FastAPI 示例",
docs_url="/docs",
redoc_url="/redoc"
)
class User(BaseModel):
id: int
username: str
email: EmailStr
age: int
is_active: bool = True
model_config = {
"json_schema_extra": {
"examples": [{
"id": 1,
"username": "john",
"email": "john@example.com",
"age": 30,
"is_active": True
}]
}
}
fake_db = [
{"id": 1, "username": "john", "email": "john@example.com", "age": 30, "is_active": True}
]
@app.get("/users/", tags=["用户"], response_model=list[User])
def list_users():
"""获取所有用户"""
return fake_db
@app.post("/users/", tags=["用户"], response_model=User, status_code=201)
def create_user(user: User):
"""创建新用户"""
if any(u["username"] == user.username for u in fake_db):
raise HTTPException(400, "用户名已存在")
fake_db.append(user.dict())
return user
十一、进阶:自定义 Swagger UI
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.staticfiles import StaticFiles
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/docs", include_in_schema=False)
def custom_swagger_ui():
return get_swagger_ui_html(
openapi_url="/openapi.json",
title="自定义 API 文档",
swagger_js_url="/static/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui.css"
)
下载官方资源到
static/目录,实现离线文档
十二、常见问题
| 问题 | 解决方案 |
|---|---|
/docs 404 | 检查是否设置了 docs_url=None |
| 示例不显示 | 使用 model_config["json_schema_extra"]["examples"] |
| 文档乱码 | 确保使用 UTF-8 编码 |
| 想导出 PDF | 使用 ReDoc + 浏览器打印 |
总结:FastAPI 文档优势
| 特性 | 说明 |
|---|---|
| 零成本 | 写 API = 写文档 |
| 实时更新 | 代码改,文档自动更新 |
| 可交互 | 直接在浏览器测试 |
| 标准输出 | OpenAPI JSON 可生成 SDK |
| 美观易用 | Swagger + ReDoc 双引擎 |
下一步建议
| 学习方向 | 关键词 |
|---|---|
| 生成前端类型 | TypeScript |
| 导入 Postman | Postman |
| 自动生成 SDK | SDK |
| 自定义 UI | 自定义文档 |
现在就打开 http://127.0.0.1:8000/docs,体验交互式 API 吧!
需要我帮你 生成一个带完整文档的项目模板(包含分组、示例、描述)吗?
回复 文档模板 立刻获取!