You could specify the range from -1
to 168
and also have a custom Pydantic validator to check whether or not the value is equal to 0
. If so, raise ValueError
. If the Pydantic model was instead used to define query parameters for the endpoint (using Depends()
), please have a look at this answer.
Example
from fastapi import FastAPI
from typing import Optional
from pydantic import Field, BaseModel, validator
app = FastAPI()
class Foo(BaseModel):
item: Optional[int] = Field(None, ge=-1, le=168)
@validator('item')
def prevent_zero(cls, v):
if v == 0:
raise ValueError('ensure this value is not 0')
return v
@app.post("/")
def submit(foo: Foo):
return foo