响应侧:response_model 是文档的基础(续)
即使是从多个数据源组装的场景,道理也一样——返回字典就够了:
@router.get("/dashboard", response_model=DashboardResponse)
async def get_dashboard():
user = await users_repo.get_current_user()
stats = await analytics_service.get_user_stats(user.id)
# 返回字典,让 response_model 负责验证和序列化
return {
"username": user.username,
"post_count": stats.post_count,
"follower_count": stats.follower_count,
}
所以原则只有一条:只要声明了 response_model,就让框架去做验证和序列化,路由只负责返回原始数据。无论数据来自单个 ORM 对象、一个字典,还是从多个来源组装出来的结果,都不需要你自己先手动构造一遍 Pydantic 对象。
把响应链路理解为两层会更清楚:
- 业务层决定"返回什么数据"(ORM 对象、字典、组装结果)
- API 层决定"对外暴露成什么结构"(
response_model负责)
这样你就不会把 response_model 用成内部业务模型,也不会为了"类型统一"到处做重复转换。
response_model 不适用的场景
response_model 的前提是路由返回的是可以被 Pydantic 序列化的数据。当你返回一个 Response 对象的子类时,FastAPI 会完全跳过 response_model 的序列化步骤——即使你声明了,也不会生效。
最常见的两类情况:
文件下载:返回 FileResponse 时,response_model 无效。用 response_class 告知文档类型即可: