OpenAPITools / openapi-generator

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
https://openapi-generator.tech
Apache License 2.0
21.15k stars 6.41k forks source link

[BUG] [Python] to_json function raise error on date type #18397

Open imyixiao opened 4 months ago

imyixiao commented 4 months ago

Bug Report Checklist

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
  1. generate sdk with the spec and version 7.4
  2. 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
alfechner commented 4 months ago

I have the exact same issue.

This is my work around for now:

json.dumps(pipeline.to_dict(), default=str)
imyixiao commented 4 months ago

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)
bgunebakan commented 4 months ago

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)
wing328 commented 4 months ago

Do you mind submitting a PR with the suggested change?

bilaltonga commented 4 months ago

Do you mind submitting a PR with the suggested change?

Actually I'm preparing a PR with this change.