Fastapi: 500 is returned instead of 422 when using Depends

Created on 27 Oct 2020  路  4Comments  路  Source: tiangolo/fastapi

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?

Most helpful comment

alternatively,

  • you can use HTTPException inside the validator with 422 (HTTP_422_UNPROCESSABLE_ENTITYor etc) status code.
  • or put CommonParams in the Body.

All 4 comments

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,

  • you can use HTTPException inside the validator with 422 (HTTP_422_UNPROCESSABLE_ENTITYor etc) status code.
  • or put CommonParams in the Body.

Hi,

maybe this answer helps, i think those issues are related:

https://github.com/tiangolo/fastapi/issues/2180#issuecomment-713626409

Was this page helpful?
0 / 5 - 0 ratings