繁体   English   中英

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

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

这是继续这个问题

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

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 中

在此处输入图像描述

但是如果同样的 model 被用于 request body,那么 description 显示在 swagger

在此处输入图像描述

我是否遗漏了在 swagger ui 中获取 QueryParams(model) 描述的任何内容?

这对于 Pydantic 模型是不可能的

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

from fastapi import Depends, FastAPI, Query

app = FastAPI()


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


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

因此,您将拥有该文档,

截屏


参考

  1. 在 FastAPI 中验证 GET 参数--(FastAPI GitHub)似乎对扩展 Pydantic 模型来验证 GET 参数的兴趣不大
  2. 作为依赖项的类--(FastAPI Doc)

接受的答案是指使用自定义依赖项,使用 FastAPI 类作为依赖项来批量定义查询参数,虽然我认为它工作得很好,但我觉得在这种情况下使用数据类会更好,并且减少代码重复,因为__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 端点之一一样,这很快就会变得很麻烦。

使用数据类作为依赖

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

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

这对我有用


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"


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM