DEV Community

Discussion on: FastAPI - The Good, the bad and the ugly.

Collapse
 
matixezor profile image
Mateusz Romański

@fuadrafid
Actually to pass validation error message you can just use pydantic @validator decorator. For example:

class User(BaseModel):
    phone: str

    @validator('phone')
    def phone_validator(cls, v):
        if v and len(v) != 9 or not v.isdigit():
            raise ValueError('Invalid phone number')
        return v
Enter fullscreen mode Exit fullscreen mode

Then on validation error this will be the response body:

{
  "detail": [
    {
      "loc": [
        "body",
        "phone"
      ],
      "msg": "Invalid phone number",
      "type": "value_error"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
fuadrafid profile image
Muhtasim Fuad Rafid • Edited

Thank you for reading!
You are suggesting custom validators, I was talking about the default validators provided by pydantic. These work fine, but image having a project with 50+ dataclasses, writing validators for each of the variables isn't really efficient.
You can see Springboot's validators. A simple message inside the annotation itself, simple and efficient.