Search code examples
pythonswagger-uifastapipydantic

FastAPI: Add description to a class based request parameter / filter


I'm using this model class that specifies the different input parameters one can use to filter a result list of an endpoint:

from pydantic import BaseModel

class MyFilter(BaseModel):
    status: Optional[ValidationStatus]
    reference: Optional[str]
    include_documents: Optional[bool]

Same as for my input model fields I would like to add description strings to the SwaggerUI to explain the meaning e.g. specifically for include_documents.

My endpoint looks like:

def get_list(
    request: Request, my_filter: MyFilter = Depends(), db: Session = Depends(get_db)
):

I see in the docs only that a description is possible using Query for a parameter overall but not how I would do it for each "field" in my model. Is that possible?

When I try Query or Path in my method signature I get the error message: Param: my_filter can only be a request body, using Body()


Solution

  • I found a solution/workaround in a github issue of fastapi: https://github.com/tiangolo/fastapi/issues/4700

    This works for me:

    from fastapi import Query
    
    class MyFilter(BaseModel):
        include_documents: Optional[bool] = Query(Query(description="hello", default=None))
    

    Note: Without default=None it will be marked as required despite the Optional.