FastAPI 响应模型:Pydantic 的数据验证与转换,一篇吃透!

是否遇到过这些问题?

数据库返回字段太多,前端只要几个?接口文档不一致,测试老是报错?ORM 对象直接返回,总是类型错误?

快用 FastAPI 的响应模型(response_model)+ Pydantic,自动校验、转换、过滤、文档全搞定!

1. 什么是响应模型?

响应模型用于定义接口的返回结构。FastAPI 会根据响应模型:

自动校验字段类型自动过滤多余字段自动转换格式自动生成文档(OpenAPI)2. 快速上手:定义响应结构
复制
from pydantic import BaseModel class UserOut(BaseModel): id: int name: str email: str1.2.3.4.5.6.

在接口中使用:

复制
from fastapi import FastAPI app = FastAPI() @app.get("/users/{user_id}", response_model=UserOut) def get_user(user_id: int): return { "id": user_id, "name": "Alice", "email": "alice@example.com", "is_admin": True # 会自动被过滤掉 }1.2.3.4.5.6.7.8.9.10.11.12.

最终返回只包含指定字段:

复制
{ "id": 1, "name": "Alice", "email": "alice@example.com" }1.2.3.4.5.
3. 支持嵌套模型和列表模型
复制
class Address(BaseModel): city: str country: str class UserOut(BaseModel): id: int name: str address: Address1.2.3.4.5.6.7.8.

列表结构也支持:

复制
@app.get("/users/", response_model=list[UserOut]) def get_users(): return [...]1.2.3.
4. ORM 模式(必须开启):与数据库模型打通

如果你使用 SQLAlchemy、Tortoise ORM 等,接口函数中返回的是 ORM 实例而不是字典,就必须开启 “ORM 模式”。

为什么要开启?

因为 ORM 对象不是标准字典,Pydantic 默认不能识别对象的属性,需要开启专用模式:

(1) Pydantic v1 的写法

复制
class UserOut(BaseModel): id: int name: str class Config: orm_mode = True1.2.3.4.5.6.

FastAPI 会自动调用 obj.__dict__ 或属性方法,提取字段。

(2) Pydantic v2 的写法(推荐)

复制
class UserOut(BaseModel): id: int name: str model_config = { "from_attributes": True # 替代 orm_mode }1.2.3.4.5.6.7.

from_attributes=True 更加清晰地表明“这个模型的字段可以从属性中提取”。

(3) 搭配 SQLAlchemy 使用示例

复制
from sqlalchemy.orm import declarative_base from sqlalchemy import Column, Integer, String Base = declarative_base() class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) name = Column(String) # 响应模型 class UserOut(BaseModel): id: int name: str model_config = { "from_attributes": True } @app.get("/users/{id}", response_model=UserOut) def get_user(id: int, db: Session = Depends(get_db)): return db.query(User).get(id)1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.

(4) 搭配 Tortoise ORM 使用示例

复制
from tortoise.models import Model from tortoise import fields class User(Model): id = fields.IntField(pk=True) name = fields.CharField(max_length=50) class UserOut(BaseModel): id: int name: str model_config = { "from_attributes": True } @app.get("/users/{id}", response_model=UserOut) async def get_user(id: int): user = await User.get(id=id) return user1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.
 5. 响应字段别名与描述(自动生成文档)
复制
from pydantic import Field class UserOut(BaseModel): id: int name: str = Field(..., alias="username", description="用户名")1.2.3.4.5.

返回结构变为:

复制
{ "id": 1, "username": "Alice" }1.2.3.4.

在 Swagger 文档中也能自动显示字段描述!

6. Pydantic v1 vs v2 对比

功能点

v1

v2(推荐)

底层实现

Python 实现

Rust 实现(pydantic-core)

性能

一般

🚀 提升 5~50 倍

默认值声明

可用 =

推荐使用 Field() 显式写法

ORM 支持

Config.orm_mode = True

model_config = {"from_attributes": True}

JSON 解析

Python 实现

快速原生 JSON 序列化

联合类型支持

较弱

强化了对 Union, Annotated 的支持

7. 总结

response_model 是 FastAPI 最强大功能之一,搭配 Pydantic 使用,自动:

校验字段过滤无用字段自动格式转换自动生成 Swagger 文档无缝对接 ORM 模型对象

ORM 模式配置(orm_mode 或 from_attributes)一定不能忘,否则可能会返回空数据、字段丢失等问题。

阅读剩余
THE END