使用 Pydantic 模型(FastAPI)在 swagger 文档中设置查询参数的描述

Set description for query parameter in swagger doc using Pydantic model (FastAPI)

这是继续

我添加了一个模型来获取 pydantic 模型的查询参数

class QueryParams(BaseModel):
    x: str = Field(description="query x")
    y: str = Field(description="query y")
    z: str = Field(description="query z")


@app.get("/test-query-url/{test_id}")
async def get_by_query(test_id: int, query_params: QueryParams = Depends()):
    print(test_id)
    print(query_params.dict(by_alias=True))
    return True

它按预期工作,但描述(添加到模型中)没有反映在 swagger 中 ui

但是如果request body使用相同的model,那么描述会以swagger显示

我是否遗漏了任何东西来大摇大摆地获取 QueryParams(model) 的描述 ui?

Pydantic 模型无法做到这一点

获得所需结果的解决方法是使用 自定义依赖项 class(或函数) 而不是学究模型

from fastapi import Depends, FastAPI, Query

app = FastAPI()


<b>class CustomQueryParams:
    def __init__(
        self,
        foo: str = Query(..., description="Cool Description for foo"),
        bar: str = Query(..., description="Cool Description for bar"),
    ):
        self.foo = foo
        self.bar = bar</b>


@app.get("/test-query/")
async def get_by_query(<b>params: CustomQueryParams = Depends()</b>):
    return params

因此,您将获得文档,


参考资料

  1. Validate GET parameters in FastAPI--(FastAPI GitHub) 似乎人们对扩展 Pydantic 模型 以验证 GET 参数
  2. 的兴趣不大
  3. Classes as Dependencies--(FastAPI Doc)

这对我有用


from fastapi import Depends, FastAPI, Query

@app.post("/route")
def some_api(
        self,
        query_param_1: float = Query(None, description="description goes here", ),
        query_param_2: float = Query(None, description="Param 2 does xyz"),
):
    
return "hello world"


接受的答案是指使用 FastAPI classes as dependencies to define the query parameters in bulk and while I think it works great, I feel the using dataclasses 的自定义依赖项在这种情况下会更好,并且会减少代码重复,因为 __init__ 将自动生成。

正常class作为依赖

class QueryParams:
    def __init__(self, 
    x:  Query(
            None, description="Arg1", example=10),
    y:  Query(
            None, description="Arg2", example=20)
    ):
        self.x = x
        self.y = y

虽然对于较少数量的查询参数,这样做会很好,但如果参数数量很大,就像我的 api 端点之一一样,这很快就会变得很麻烦.

使用数据class作为依赖项

@dataclass
class QueryParams:
    x:  Query(None, description="Arg1", example=10)
    y:  Query(None, description="Arg2", example=20)

此外,如果您需要更复杂的功能,您还可以添加数据classes。