fastapi: 封装接口的数据返回格式,支持文档显示数据格式

📅 2026/7/24 21:56:40 👁️ 阅读次数 📝 编程学习
fastapi: 封装接口的数据返回格式,支持文档显示数据格式

一,代码:

返回数据用的泛型封装类:

# 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 ApiResponse(BaseModel, Generic[T]):code: int = 200message: str = "success"data: Optional[T] = None  # data 可以是任意类型 T# 便捷的类方法,方便业务代码调用# 返回成功数据@classmethoddef success(cls, data: Optional[T] = None, message: str = "success"):return cls(code=200, message=message, data=data)# 返回失败数据@classmethoddef fail(cls, code: int = 400, message: str = "fail"):return cls(code=code, message=message, data={})

接口调用:

# 输出给前端的用户信息(安全公开,不含密码,包含只读字段)
class UserResponse(BaseModel):id: int = Field(..., description="用户的唯一ID")username: str = Field(..., description="用户名")nickname: str = Field(..., description="用户昵称")class Config:from_attributes = Truejson_schema_extra = {"example": {"id": 1, "username": "alex_green", "nickname": "alex@example.com"}}# 这是你需要补上的分页响应模型
class UserListPageResponse(BaseModel, Generic[T]):total: intitems: List[T] # 核心:这里告诉 Pydantic,items 里面才是用户列表@router.get("/all2", response_model=ApiResponse[UserListPageResponse[UserResponse]], summary="获取商品和用户数据")
async def get_all_users2(request: Request,prod_data: Annotated[UserListForm, Query()],db: AsyncSession = Depends(get_db)):# 参数page = prod_data.pagepage_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_countitems = [row.User for row in rows]# 数据data = {"items": items,"total": total,}# return ApiResponse.fail(code=403,message="测试报错")return ApiResponse.success(data=data)

 

二,测试效果:

数据返回

image

文档:

image