簡體   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