My GET endpoint receives a query parameter that needs to meet the following criteria:
- be an
intbetween 0 and 10 - be even number
1. is straight forward using Query(gt=0, lt=10). However, it is not quiet clear to me how to extend Query to do extra custom validation such as 2.. The documentation ultimately leads to pydantic. But, my application runs into internal server error when the second validation 2. fails.
Below is a minimal scoped example
from fastapi import FastAPI, Depends, Query
from pydantic import BaseModel, ValidationError, validator
app = FastAPI()
class CommonParams(BaseModel):
n: int = Query(default=..., gt=0, lt=10)
@validator('n')
def validate(cls, v):
if v%2 != 0:
raise ValueError("Number is not even :( ")
return v
@app.get("/")
async def root(common: CommonParams = Depends()):
return {"n": common.n}
Below are requests that work as expected and ones that break:
# requsts that work as expected
localhost:8000?n=-4
localhost:8000?n=-3
localhost:8000?n=2
localhost:8000?n=8
localhost:8000?n=99
# request that break server
localhost:8000?n=1
localhost:8000?n=3
localhost:8000?n=5