Replies: 4 comments
-
I tried to specify a "422" in the response but that does not seem to make a difference:
|
Beta Was this translation helpful? Give feedback.
-
@atistler Why you need override response 422?Can you write a simple demo. Pydantic validation errors will be raised when validate pydantic model, refer to https://github.com/luolingchun/flask-openapi3/blob/master/flask_openapi3/request.py#L134-L134 |
Beta Was this translation helpful? Give feedback.
-
Because all other http errors in my application are structured in the following way:
I would like to maintain that consistency. I guess i could write a decorator wrapping the app.post() that catches the pydantic validation error. I would seem that flask-openapi3 shouldn't make assumptions about how the 422 should be rendered as an http response though. |
Beta Was this translation helpful? Give feedback.
-
We have drafted a PR (Be able to change 422 validation errors to other http response status code) to discuss the 422 UnprocessableEntity response, So we can merge and solve this problem. My idea is to add
from pydantic import ValidationError, BaseModel
class ValidationErrorModel(BaseModel):
code: str,
message: str
def validation_error_callback(e: ValidationError):
validation_error_object = ValidationErrorModel(code="400", mmessage=e.json())
response = make_response(validation_error_object.json())
response.headers["Content-Type"] = "application/json"
response.status_code = getattr(current_app, "validation_error_status", 422)
return response
app = OpenAPI(__name__, validation_error_status=422, validation_error_model=ValidationErrorModel, validation_error_callback=validation_error_callback) And then change the logic of request. try:
# Validate header, cookie, path, and query parameters
if header:
_do_header(header, func_kwargs)
if cookie:
_do_cookie(cookie, func_kwargs)
if path:
_do_path(path, path_kwargs, func_kwargs)
if query:
_do_query(query, func_kwargs)
if form:
_do_form(form, func_kwargs)
if body:
_do_body(body, func_kwargs)
except ValidationError as e:
# Create a JSON response with validation error details
validation_error_callback = getattr(current_app, "validation_error_callback", None)
if validation_error_callback:
response = validation_error_callback(e)
else:
response = make_response(e.json())
response.headers["Content-Type"] = "application/json"
response.status_code = getattr(current_app, "validation_error_status", 422)
return response |
Beta Was this translation helpful? Give feedback.
-
Currently pydantic validation errors are rendered something like this:
422 UnprocessableEntity
Is there anyway to override this behavior and make the response body customizable specifically for 422's when the body is invalid.
Beta Was this translation helpful? Give feedback.
All reactions