Answer a question

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

enter image description here

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

enter image description here

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

Answers

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,

screenshot


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)
Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐