user13716143
user13716143

Reputation:

Validate int arguments for FastAPI?

I have a ratings system in my post method. I only want the range to be 1-10, anything else, would return an error, I have this in my BaseModel, so I'm not sure how to handle this (https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/ doesn't show an example). If I can get some help that would be great!

Code:

class Rating(BaseModel):
  name: str
  rate: int (I want to validate that this is in range to 1-10)

data = []

@app.post("/Rating")
async def add_rate(rating: Rating):
  data.append(rating.dict())
  return data[-1]

Upvotes: 2

Views: 3363

Answers (1)

finswimmer
finswimmer

Reputation: 15242

data = []


class Rating(BaseModel):
  name: str
  rate: int = Field(ge=1, le=10)


@app.post("/Rating")
async def add_rate(rating: Rating):
  data.append(rating.dict())
  return data[-1]

Upvotes: 4

Related Questions