Search code examples
pythonfastapiswagger-uidepends

Fastapi - need to use both Body and Depends as default value


I have an endpoint in in which the main body parameter was defined as follows:

@router.post("/myendpoint")
async def delete_objectss(param: DeleteItemParams = DeleteItemParamsMetadata, 
                          .....)

Reason behind this is that I needed:

DeleteItemParamsMetadata = Body(None, description="my verbose description  " \
" that will appear on swaggerui under the schema of this parameter")

Now I have a need for performing some custom checks when I receive this parameter, in order to have that dependency sorted, I could replace my param definition within /myendpoint as follows:

@router.post("/myendpoint")
async def delete_objectss(param: DeleteItemParams = Depends(validate_param), 
                          .....)

or course where I have somewhere a definition

def validate_param(param: DeleteItemParams):
 if bla_bla: # lenghty and complex condition
    raise HTTPException(status_code=422, detail="Invalid item")
 
 param = possibly_alter_param_in_some_way(param)

 return param

The problem I have now, is that as far as I know Depends does not support a description field, so I now lost my verbose description that would have appeared on swaggerui.

Does anyone know of a way so I can have the best of both worlds and have the dependency pulled AND the description processed?

Thank you to anyone who has any input!


Solution

  • A parameter in a dependency can have a Body reference (or any other type) and it will be resolved correctly. Since you removed that metadata reference in your example it won't show up. You can fix that by adding it back:

    DeleteItemParamsMetadata = Body(None, description="my verbose description  " \
    " that will appear on swaggerui under the schema of this parameter")
    
    def validate_param(param: DeleteItemParams = DeleteItemParamsMetadata):
    

    or directly inline:

    def validate_param(param: DeleteItemParams = Body(None, description="my verbose description that will appear on swaggerui under the schema of this parameter")):