-
DescriptionHow can I use validation on fields of model ? I wrote my code with this inspiration : discussion on #312 from fastapi import FastAPI
from pydantic import BaseModel, ValidationError, validator, Schema
from typing import List
app = FastAPI()
class Item(BaseModel):
v1: float = Schema(0, gte=-90, lte=90)
v2: float
@validator('v1' , 'v2')
def check_value(cls, v):
if v < 0 or v > 10:
raise ValueError(f'error value')
return v
class ListItem(BaseModel):
data: List[Item] = None
@app.post("/items/")
async def create_item(item: ListItem):
nb_items = len(item.data)
the_sum = 0
i = 0
while (i < nb_items):
l1 = item.data[i]
the_sum += l1.v1 * 1.5 / l1.v2;
i += 1
return {"result": the_sum }Thanks in advance for help. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
|
Well, since you define it at the function signature level, usually FastAPI will help you validate against Pydantic validation rules and raise HTTP error appropriately before executing your router function, so you cannot If you need it to be more flexible, you can either
|
Beta Was this translation helpful? Give feedback.
-
|
Hi @phy25 thanks for your help. I thought that router-based validation would cause many work to have an equivalent of a pydantic validator. I worked from your second suggestion, handle error myself using a global exception handler. ...
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse
import re
class Item(BaseModel):
v1: float = Schema(0, gte=-90, lte=90)
v2: float
@validator('v1' , 'v2')
def check_value(cls, v, field):
if v < 0 or v > 10:
raise ValueError(str(field.name) + ": doit être entre [0; 10]")
return v
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
errors = str(exc).splitlines()
justErrorText = re.compile(r'(.+)\s+(\(.+\))').sub(r"\1' ", errors[2])
return PlainTextResponse(justErrorText, status_code=400)I wanted retrieve the text of valueError. That's why, i must remove informations from the second parameter of validation_exception_handler. What do you think ? maybe i could do better, and i will be delighted to have your opinion. |
Beta Was this translation helpful? Give feedback.
-
|
Thanks for the help @phy25 ! 🍰 🙇 @foulong it's in the docs, check it here: https://fastapi.tiangolo.com/tutorial/handling-errors/#use-the-requestvalidationerror-body |
Beta Was this translation helpful? Give feedback.
-
|
Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues. |
Beta Was this translation helpful? Give feedback.
Thanks for the help @phy25 ! 🍰 🙇
@foulong it's in the docs, check it here: https://fastapi.tiangolo.com/tutorial/handling-errors/#use-the-requestvalidationerror-body