FastAPI 响应模型:Pydantic 的数据验证与转换,一篇吃透!
是否遇到过这些问题?
- 数据库返回字段太多,前端只要几个?
- 接口文档不一致,测试老是报错?
- ORM 对象直接返回,总是类型错误?
快用 FastAPI 的响应模型(response_model)+ Pydantic,自动校验、转换、过滤、文档全搞定!
1. 什么是响应模型?
响应模型用于定义接口的返回结构。FastAPI 会根据响应模型:
- 自动校验字段类型
- 自动过滤多余字段
- 自动转换格式
- 自动生成文档(OpenAPI)
2. 快速上手:定义响应结构
from pydantic import BaseModel
class UserOut(BaseModel):
id: int
name: str
email: str
在接口中使用:
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 # 会自动被过滤掉
}
最终返回只包含指定字段:
{
"id": 1,
"name": "Alice",
"email": "alice@example.com"
}
3. 支持嵌套模型和列表模型
class Address(BaseModel):
city: str
country: str
class UserOut(BaseModel):
id: int
name: str
address: Address
列表结构也支持:
@app.get("/users/", response_model=list[UserOut])
def get_users():
return [...]
4. ORM 模式(必须开启):与数据库模型打通
如果你使用 SQLAlchemy、Tortoise ORM 等,接口函数中返回的是 ORM 实例而不是字典,就必须开启 “ORM 模式”。
为什么要开启?
因为 ORM 对象不是标准字典,Pydantic 默认不能识别对象的属性,需要开启专用模式:
(1) Pydantic v1 的写法
class UserOut(BaseModel):
id: int
name: str
class Config:
orm_mode = True
FastAPI 会自动调用 obj.__dict__ 或属性方法,提取字段。
(2) Pydantic v2 的写法(推荐)
class UserOut(BaseModel):
id: int
name: str
model_config = {
"from_attributes": True # 替代 orm_mode
}
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)
(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 user
5. 响应字段别名与描述(自动生成文档)
from pydantic import Field
class UserOut(BaseModel):
id: int
name: str = Field(..., alias="username", description="用户名")
返回结构变为:
{
"id": 1,
"username": "Alice"
}
在 Swagger 文档中也能自动显示字段描述!
6. Pydantic v1 vs v2 对比
功能点 | v1 | v2(推荐) |
底层实现 | Python 实现 | Rust 实现(pydantic-core) |
性能 | 一般 |
本文地址:https://www.yitenyun.com/106.html 最新文章热门文章 |