You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中Pydantic Model参数描述未在OpenAPI显示的解决方法

解决FastAPI分页参数类的OpenAPI描述不显示问题

问题分析

你用BaseModel封装了分页参数类PaginatedParams,通过Depends注入路由后,OpenAPI文档里看不到page和size的参数描述,但单独定义的query参数显示正常。这是因为FastAPI默认会把通过Depends注入的BaseModel识别为请求体参数,而非查询参数,所以不会在查询参数区域展示描述。

修复方案

1. 修正参数类代码

补全缺失的导入,确保字段用Annotated结合Query正确标注,同时完善验证逻辑的依赖:

from fastapi import Query, HTTPException, HTTPStatus
from pydantic import BaseModel
from typing import Annotated

class PaginatedParams(BaseModel):
    page: Annotated[int, Query(1, description='Page number')]
    size: Annotated[int, Query(10, description='Number of records per page')]

    def validate(self):
        if self.page < 1:
            raise HTTPException(
                status_code=HTTPStatus.BAD_REQUEST,
                detail="Page number must be greater than 0",
            )
        if self.size < 1:
            raise HTTPException(
                status_code=HTTPStatus.BAD_REQUEST,
                detail="Size number must be greater than 0",
            )

2. 调整路由注入方式

在路由中注入参数类时,FastAPI会根据字段上的Query标注自动识别为查询参数,注入后手动调用验证方法:

from fastapi import APIRouter, Depends, Query

@router.get(
    '/search',
    response_model=dict[str, list[FilmsListApi] | int | str],
    description='Search films by its title.',
)
async def search_films(
        params: PaginatedParams = Depends(),
        query: str = Query('', description='The keywords for searching films'),
        film_service: FilmService = Depends(get_film_service),
) -> dict[str, list[FilmsListApi] | int | str]:
    params.validate()
    # 业务逻辑代码

关键说明

  • FastAPI 0.95+版本会自动识别BaseModel字段上的Query标注,将其解析为查询参数,无需额外配置。
  • 必须确保Annotated、BaseModel等依赖正确导入,否则会导致参数解析异常或报错。

内容的提问来源于stack exchange,提问作者Lelouch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 05:15:28