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

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

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

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

响应侧:response_model 是文档的基础(续)

原则 2:字段加描述,让文档更完整

class UserResponse(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: int = Field(description="用户 ID")
    username: str = Field(description="用户名")
    email: EmailStr = Field(description="邮箱地址")
    is_active: bool = Field(description="账户是否激活")

这些 description 会直接显示在 OpenAPI 文档里,帮助前端理解每个字段的含义。

原则 3:用 from_attributes=True 兼容 ORM 对象

class UserResponse(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: int
    username: str

这个配置让 Pydantic 可以直接从 ORM 对象读取属性,不需要手动转换成字典。路由里可以直接返回 ORM 对象,框架会自动用 response_model 做转换和过滤。

小模型可以留在 router.py

并非所有响应模型都需要放进 schemas.py。如果一个响应模型满足这些条件:

那么直接定义在 router.py 里通常更合理,这样接口逻辑和数据结构在一起,更容易维护: