Validation with dataclass #21
-
|
A simple function to validate a string using a dataclass:
The # 2 response is what I would expect. It looks like in # 1, the The solution is to change the dataclass type of objects to be validated to |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
|
Firstly, this is more a question for fastapi/pydantic repositories. It is unrelated to error handling. But 1, is the more correct code I would say here, let pydantic validate your inputs. The joy of fastapi/pydantic is not having to check for valid input types and letting the system raise for you. It is occurring because you have told fastapi you expect a string, and it is checking (and failing) before you hit your internal code that then checks the data type to raise your custom RequestValidationError. I would also recommend not raising starlette.RequestValidationError as you are then raising it in a format it is not intended to be used in (as you can see from the standard format of the error compared to your expected format). Essentially your internal check is made redundant by the external pydantic check. If mystring can be an integer in some cases and not others, then I would create two different classes one that accepts If it is not allowed and you only want strings, then there is no need for the type check and just let fastapi pydantic your inputs. |
Beta Was this translation helpful? Give feedback.
pydantic is baked into fastapi essentially, but definitely make use of v2 as that is the default version in fastapi these days.
To get consistent error messages like that, you can just reply on well defined schemas for your endpoint inputs