pythonfastapipydantic

with Pydantic, how can i create my own ValidationError reason


it seems impossible to set a regex constraint with a __root__ field like this one:

class Cars(BaseModel):
    __root__: Dict[str, CarData]

so, i've resorted to doing it at the endpoint:

@app.post("/cars")
async def get_cars(cars: Cars = Body(...)):
    x = cars.json()
    y = json.loads(x)
    keys = list(y.keys())
    try:
        if any([re.search(r'^\d+$', i) is None for i in keys]):
            raise ValidationError
    except ValidationError as ex:
        return 'wrong type'
    return 'works'

this works well in that i get wrong type returned if i dont use a digit in the request body.

but i'd like to return something similar to what pydantic returns but with a custom message:

{
  "detail": [
    {
      "loc": [
        "body",
        "__root__",
      ],
      "msg": "hey there, you can only use digits!",
      "type": "type_error.???"
    }
  ]
}

Solution

  • You can pass your own error string by using raise ValidationError("Wrong data type"). Hope it helps.