0%

FastAPI自学教程(18) - 响应模型

1. 基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
name: str
description: str | None = None
price: float

@app.post("/items/", response_model=Item)
async def create_item(item: Item):
return item
  • 使用 response_model 参数声明响应模型(路径操作装饰器参数,非函数返回注解)
  • 支持所有 HTTP 方法(GET/POST/PUT/DELETE 等)
  • 核心功能:
    • 数据转换与验证
    • 自动生成 OpenAPI Schema
    • 文档系统集成
    • 输出数据限制

2. 模型分离场景

1
2
3
4
5
6
7
8
9
10
class UserIn(BaseModel):
username: str
password: str # 敏感字段

class UserOut(BaseModel):
username: str # 过滤密码字段

@app.post("/users/", response_model=UserOut)
async def create_user(user: UserIn):
return user
  • 请求模型与响应模型分离,避免敏感数据泄露
  • Pydantic 自动过滤未在响应模型中声明的字段
  • 支持嵌套模型(如 list[Item] 列表结构)

3. 高级配置参数

1
2
3
4
5
6
@app.get("/items/", 
response_model=Item,
response_model_exclude_unset=True,
response_model_include={"name", "price"})
async def read_item():
return Item(name="Foo", price=35.4, description="Test")
  • response_model_exclude_unset:排除未显式设置的默认值字段
  • response_model_include/exclude:字段白名单/黑名单控制
  • response_model_exclude_none:排除值为 None 的字段

4. ORM 模型转换

1
2
3
4
5
6
7
class UserBase(BaseModel):
class Config:
orm_mode = True

@app.get("/users/", response_model=list[UserBase])
async def get_users():
return db.query(User).all() # 自动转换 SQLAlchemy 对象
  • 启用 orm_mode 支持数据库模型到 Pydantic 模型的自动转换
  • 结合 to_dict() 方法处理复杂 ORM 对象

5. 注意事项

  • 优先级规则response_model 优先级高于函数返回类型注解
  • 文档交互:Swagger UI 自动展示响应模型结构,但无法直接测试嵌套模型
  • 数据验证:响应数据不符合模型时会触发 500 错误
  • 性能影响:复杂模型嵌套可能增加序列化开销