bauerji / flask-pydantic

flask extension for integration with the awesome pydantic package
MIT License
352 stars 56 forks source link

Raise classical Pydantic ValidationError like FastApi #71

Open Merinorus opened 1 year ago

Merinorus commented 1 year ago

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:

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 commented 1 year ago

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).