HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

05-让 FastAPI 接口更专业:文档契约、response_model 和模型组织

第 12 / 24 段:响应侧:`response_model` 是文档的基础

FastAPI 工程化实践 · 发布 2026-03-28 · 更新 2026-11-11 · 标签:FastAPI、Pydantic、OpenAPI

响应侧: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 对象。

把响应链路理解为两层会更清楚:

这样你就不会把 response_model 用成内部业务模型,也不会为了"类型统一"到处做重复转换。

response_model 不适用的场景

response_model 的前提是路由返回的是可以被 Pydantic 序列化的数据。当你返回一个 Response 对象的子类时,FastAPI 会完全跳过 response_model 的序列化步骤——即使你声明了,也不会生效。

最常见的两类情况:

文件下载:返回 FileResponse 时,response_model 无效。用 response_class 告知文档类型即可: