请求侧:让参数自解释
很多项目的请求参数在文档里长这样:一个参数名,一个类型,没了。前端要么靠猜,要么去翻代码,要么来问你。
FastAPI 提供了足够多的方式让请求参数在文档里自解释,但需要你主动去用。
给路径参数和查询参数加描述
最直接的方式是用 Path() 和 Query() 的 description 和 example:
from fastapi import Path, Query
@router.get("/posts/{post_id}/comments")
async def list_comments(
post_id: int = Path(description="文章 ID"),
page: int = Query(default=1, ge=1, description="页码,从 1 开始"),
size: int = Query(default=20, ge=1, le=100, description="每页数量,最大 100"),
):
...
对比不加描述的写法:
# 文档里只显示 post_id: int, page: int, size: int
# 前端不知道 page 从 0 还是 1 开始,不知道 size 上限是多少
@router.get("/posts/{post_id}/comments")
async def list_comments(post_id: int, page: int = 1, size: int = 20):
...
差别不大,但文档的可用性差很多。ge=1、le=100 这类约束不只是校验,它们也会体现在 OpenAPI schema 里,前端可以直接用来做表单校验。
用 Enum 让可选值自文档化
如果一个参数只有几个合法值,用字符串接收再手动校验是最差的选择——文档里完全看不出有哪些选项: