luolingchun / flask-openapi3

Generate REST API and OpenAPI documentation for your Flask project.
https://luolingchun.github.io/flask-openapi3/
MIT License
189 stars 29 forks source link

Allow 422 response to specified model not only array #137

Open p3rs1st opened 9 months ago

p3rs1st commented 9 months ago

In flask-openapi3, I can only specify the item of 422 response array, but I want the response of 422 is a object.

luolingchun commented 9 months ago

422 is caused by the ValidationError of Pydantic, which defaults to an array.

Why do you encounter situations where it is not an array?

Can you paste a code example?

p3rs1st commented 9 months ago

For example, when I receive a ValidationError, I want to make the response as a JSON form like

{
  "success": False,
  "msg": "Validation Error detail message here"
}

But I can only change the array item which is the parameter 'validation_error_model' of OpenAPI like

[{
  "success" False,
  "msg": "one Validation Error detail message"
}]
luolingchun commented 9 months ago

flask-openapi3 generates a default ValidationError class from Pydantic. Of course you can change it, you can change the response body model of each API, and you can change the global response body model.

class Model422(BaseModel):
    success: bool
    msg: str

# global response body model
app = OpenAPI(__name__, responses={422:Model422})

# the response body model of each API
@app.post("/", responses={200: UnionRespResp2,422:Model422})
def book(body: Resp):
    ...

Here is more information for ValidationError.