openapi-generator
openapi-generator copied to clipboard
[BUG] [Python] to_json function raise error on date type
Bug Report Checklist
- [x] Have you provided a full/minimal spec to reproduce the issue?
- [x] Have you validated the input using an OpenAPI validator (example)?
- [x] Have you tested with the latest master to confirm the issue still exists?
- [x] Have you searched for related issues/PRs?
- [x] What's the actual output vs expected output?
- [] [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description
[BUG] [Python] to_json function raise error on date type: TypeError: Object of type date is not JSON serializable
openapi-generator version
7.4
OpenAPI declaration file content or url
openapi: 3.0.0
info:
title: API
description: API
version: 1.4.0
paths:
/create:
post:
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/Pet"
responses:
"202":
description: OK
components:
schemas:
Pet:
type: object
properties:
asOfDate:
format: date
type: string
color:
type: string
Generation Details
Steps to reproduce
- generate sdk with the spec and version 7.4
- use the code below to test it
pet_dict = {
"color": "blue",
"asOfDate": "2020-03-03"
}
pet = SDK.Pet.from_json(json.dumps(pet_dict))
print(pet)
// error: Object of type date is
not JSON serializable
pet.to_json()
Related issues/PRs
Suggest a fix
I have the exact same issue.
This is my work around for now:
json.dumps(pipeline.to_dict(), default=str)
my workaround is editing the model_generic.mustache
def to_json(self) -> str:
_dict_res = self.to_dict()
for k, v in _dict_res.items():
if isinstance(v, (generic_datetime.date, generic_datetime.datetime)):
_dict_res[k] = v.isoformat()
return json.dumps(_dict_res)
I created custom model_generic.mustache with new to_json() method. It works with excluded fields also.
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
excluded_fields: Set[str] = set([
{{#vendorExtensions.x-py-readonly}}
"{{{.}}}",
{{/vendorExtensions.x-py-readonly}}
{{#isAdditionalPropertiesTrue}}
"additional_properties",
{{/isAdditionalPropertiesTrue}}
])
return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields)
Do you mind submitting a PR with the suggested change?
Do you mind submitting a PR with the suggested change?
Actually I'm preparing a PR with this change.