turner-townsend / flask-pydantic-spec

An Flask OpenAPI library using Pydantic
Apache License 2.0
99 stars 19 forks source link

[BUG] Date validation #23

Open paulgirard opened 2 years ago

paulgirard commented 2 years ago

Describe the bug Can't validate a response whose pydantic validation model contains a date.

To Reproduce

Expected behavior The response is valid and should be validated.

Error Message The pydantic model is not JSON serializable

Desktop (please complete the following information):

Python Information (please complete the following information):

Additional context

I am quite new in the pydantic world. Very pleased so far and thank you for this great addition which completely meets my need.

I turned around this as I had the impression to take the lib the wrong way. Turns out the only workaround, I found is:

@app.route("/api/date_cumbersome", methods=["GET"])
@api.validate(resp=Response(HTTP_200=HistoryDate))
def working_date_validation_cumbersome():
    historyDate = HistoryDate(date=API_DATE_TODAY)
    return jsonify(json.loads(historyDate.json()))

It's actually a pydantic issue in some ways. There is no other ways (yet) to get a json ready dict (https://github.com/samuelcolvin/pydantic/issues/951#issuecomment-552463606) to feed the Flask serializer with.

Nevertheless to stumble upon this is quite confusing and frustrating. I propose a way that does not change anything to this lib but avoid this frustration: allow to pass by flask jsonify method to use pydantic json method instead. I am not very happy with this but let's consider it as a starter for discussion.

I am submitting a PR to expose the problem and my modest proposition. The PR will have tests which will expose the issue and the workaround of serializing/deserializing.