I'm using the dependency injection mechanism to define common parameters for my requests. my common params model uses a validator that makes sure only one of the boolean flags supplied is true, not both -
class CommonParams(BaseModel):
test_id: UUID
earliest: Optional[datetime]
latest: Optional[datetime]
filters: Optional[FiltersInput]
overwrite: bool = False
ignore_cache: bool = False
@validator('ignore_cache')
def validate_overwrite_or_ignore(cls, v, values):
assert not (v or values['overwrite']), 'Either "overwrite" or "ignore_cache" can be True, not both!'
@calculate_router.post("/{test_id}")
async def calculate(commons: CommonParams = Depends()):
return "this should not be printed"
As far as i understand, if my request receives true for both "overwrite" and "ignore cache" params, request should fail with a 422 validation error. But instead im receiving a 500 with the validation error printed as log.
Is that intended or am i doing something wrong?
I guess Depends works bad with pydantic's models
I think it because we want Depends to work with any Callable, not only with BaseModel. So FastAPI parses __init__ params from dependency, validates them and after that transfer back to Depends callable where validation exception happens
alternatively,
HTTPException inside the validator with 422 (HTTP_422_UNPROCESSABLE_ENTITYor etc) status code.Hi,
maybe this answer helps, i think those issues are related:
https://github.com/tiangolo/fastapi/issues/2180#issuecomment-713626409
Related enhancement issue: https://github.com/tiangolo/fastapi/issues/1474
Most helpful comment
alternatively,
HTTPExceptioninside the validator with 422 (HTTP_422_UNPROCESSABLE_ENTITYor etc) status code.