fastapi: docs用response_model添加输出数据文档
一,代码
BaseResponse.py:
通用的返回结构,以及T泛型变量的定义
# app/core/BaseResponse.py
from typing import Annotated, List, TypeVar, Generic, Optional
from pydantic import BaseModel
# 1. 定义一个泛型变量 T,代表 data 字段可能接入的任何 Pydantic 模型
T = TypeVar("T")
# 2. 统一定义最外层的结构
class BaseResponse(BaseModel, Generic[T]):
code: int = 200
message: str = "success"
data: Optional[T] = None # data 可以是任意类型 T
实际输出时,指定response_model:
# 1. 定义请求体数据模型
class UserListForm(BaseModel):
page: int = Field(default=1, gt=0, description="页数需要大于0")
page_size: int = Field(default=3, gt=0, description="每页数量需要大于0")
# 输出给前端的用户信息(安全公开,不含密码,包含只读字段)
class UserResponse(BaseModel):
id: int = Field(..., description="用户的唯一ID")
username: str = Field(..., description="用户名")
nickname: str = Field(..., description="用户昵称")
class Config:
from_attributes = True
json_schema_extra = {
"example": {"id": 1, "username": "alex_green", "nickname": "alex@example.com"}
}
# 这是你需要补上的分页响应模型
class UserListPageResponse(BaseModel, Generic[T]):
total: int
items: List[T] # 核心:这里告诉 Pydantic,items 里面才是用户列表
@router.get("/all2", response_model=BaseResponse[UserListPageResponse[UserResponse]], summary="获取商品和用户数据")
async def get_all_users2(request: Request,
prod_data: Annotated[UserListForm, Query()],
db: AsyncSession = Depends(get_db)):
# 参数
page = prod_data.page
page_size = prod_data.page_size
# 使用 func.count().over() 作为一个隐藏列
stmt = (
select(User, func.count().over().label("total_count"))
.where(User.status == 1)
.offset((page - 1) * page_size)
.limit(page_size)
)
result = await db.execute(stmt)
# 因为多查了一个 count 列,result 出来的每一行是一个元组 (User对象, total_count值)
rows = result.all()
# 解析结果
if not rows:
return {"total": 0, "page": page, "size": page_size, "items": []}
# 无论哪一行,对应的 total_count 都是一样的,取第一行的即可
total = rows[0].total_count
items = [row.User for row in rows]
raw_data = {
"code": 200, "message": "用户信息修改成功", "data": {
"items": items,
"total": total,
}
}
return raw_data
二,测试效果:

文档:

浙公网安备 33010602011771号