flask-pydantic icon indicating copy to clipboard operation
flask-pydantic copied to clipboard

Raise classical Pydantic ValidationError like FastApi

Open Merinorus opened this issue 1 year ago • 1 comments

Hello,

I'm working with this library and I found the option to raise errors (FLASK_PYDANTIC_VALIDATION_ERROR_RAISE = True).

I was expecting the same kind of error as in FastAPI/Pydantic combination:

{
   "errors":[
      {
         "loc":[
            "query",
            "request-mode"
         ],
         "msg":"field required",
         "type":"value_error.missing"
      },
      {
         "loc":[
            "body",
            "birth_date"
         ],
         "msg":"field required",
         "type":"value_error.missing"
      }
   ]
}

In Pydantic, all errors are in the errors array and the location (header, body...) is specified directly in "loc".

In Flask-Pydantic, errors are in separate folders according to the location:

{
   "body":[
      {
         "loc":[
            "birth_date"
         ],
         "msg":"field required",
         "type":"value_error.missing"
      }
   ],
   "query":[
      {
         "loc":[
            "request-mode"
         ],
         "msg":"field required",
         "type":"value_error.missing"
      }
   ]
}

The ValidationError(BaseFlaskPydanticException) exception e is raised and you can look for each group errors according to the location:

  • e.body_params
  • e.form_params
  • e.path_params
  • e.query_params

What I would like is, for instance, to add the e.errors category which contains all the errors, formatted as in the Pydantic library used by FastAPI.

Thank you!

Merinorus avatar Apr 20 '23 13:04 Merinorus

I made a "draft" pull request. Let me know if it's unclear, not useful, or not relevant at all. If you accept this, I can improve it by adding tests. I didn't measure the performance impact, maybe I could make a condition for this error generation (for instance, a flag in the config).

Merinorus avatar Apr 20 '23 13:04 Merinorus