使用Pydantic模型(FastAPI)在swagger文档中设置查询参数的描述 [英] Set description for query parameter in swagger doc using Pydantic model (FastAPI)

查看:271
本文介绍了使用Pydantic模型(FastAPI)在swagger文档中设置查询参数的描述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是此

但是如果将相同的模型用于请求正文,则说明会以粗体显示

我是否缺少任何东西来获取swagger ui中的QueryParams(模型)的描述?

解决方案

Pydantic模型无法实现

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

从fastapi导入

 依赖,FastAPI,查询应用= FastAPI() CustomQueryParams类:def __init __(自己,foo:str = Query(...,description ="foo的酷描述"),bar:str = Query(...,description ="bar的酷描述"),):self.foo = fooself.bar = bar @ app.get("/test-query/")异步定义get_by_query( params:CustomQueryParams = Depends()):返回参数 

因此,您将拥有文档,


参考文献

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

This is continue to this question.

I have added a model to get query params to 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

it is working as expected but description(added in model) is not reflecting in swagger ui

But if same model is used for request body, then description is shown in swagger

Am I missing anything to get the description for QueryParams(model) in swagger ui?

解决方案

This is not possible with Pydantic models

The workaround to get the desired result is to have a custom dependency class (or function) rather than the Pydantic model

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

Thus, you will have the doc as,


References

  1. Validate GET parameters in FastAPI--(FastAPI GitHub) It seems like there is less interest in extending the Pydantic model to validate the GET parameters
  2. Classes as Dependencies--(FastAPI Doc)

这篇关于使用Pydantic模型(FastAPI)在swagger文档中设置查询参数的描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆