I have 2 issues that I cannot tackle so far using docs/goole/stack info :-)
1) How shall I catch ValidationErrors thrown by pydantic model validator decorator when using model as query input for fastapi get query?
context:
I have a pydantic model:
class PointRankReqParams(BaseModel):
rat: Optional[Literal['2G', '3G', '4G', '5G']] = '3G'
h3resolution: Optional[int] = 5
input_srid: Optional[int] = 4326
bufferdistance: Optional[int] = 5000
x: float
y: float
@validator('h3resolution')
def h3resolution_bins(cls, v):
if v not in [4,5,6,7,8]:
raise ValueError('Hexabin size not permitted')
return v
and FastAPI func that serves GET requests:
@router.get("/point/overall", summary="GET Ranking for given location point")
async def get_ranking_for_location_point(inputparams: PointRankReqParams = Depends(),token: str = Depends(oauth2_scheme)):
logger.debug("Here I am")
return {}
Now when I curl with parameter h3resolution beyond defined range e.g
http://localhost:9000/rank/point/overall?rat=2G&h3resolution=9&input_srid=4326&bufferdistance=5000&x=21&y=21
I get errors in console that actually makes sense
py- | File "pydantic/main.py", line 406, in pydantic.main.BaseModel.__init__
py- | pydantic.error_wrappers.ValidationError: 1 validation error for PointRankReqParams
py- | h3resolution
py- | Hexabin size not permitted (type=value_error)
But FastAPI returns HTTP 500 Internal Server Error to end-client. How shall I catch those exceptions that comes from validator?
2. How to use Optional[Literal[...]] construction properly?
I've tried to redefine above example to use in model:
class PointRankReqParams(BaseModel):
...
h3resolution: Optional[Literal[4,5,6,7,8]] = 5
But when I curl GET query
e.g http://localhost:9000/rank/point/overall?rat=2G&h3resolution=7&input_srid=4326&bufferdistance=5000&x=21&y=21
I receive 422 Unprocessable entry as h3resolution is being interpreted as string not integer:
{
"detail": [
{
"loc": [
"query",
"h3resolution"
],
"msg": "unexpected value; permitted: 4, 5, 6, 7, 8",
"type": "value_error.const",
"ctx": {
"given": "7",
"permitted": [
4,
5,
6,
7,
8
]
}
}
]
}
Thanks a lot!