Multiple body-types in an endpoint with same model (referenced via `$ref`) results in ambiguity in generated code
linkdd opened this issue · 1 comments
| Python Version | OpenAPI Client Generator Version |
|---|---|
| 3.11.6 | 0.18.0 |
Actual Behavior
When an endpoint has multiple body types, each referencing the same model (via a $ref key), the generator generates the same class name for each body types, which results then in the following generated code:
def _get_kwargs(
# ...
):
# ...
if isinstance(body, WritableJournalEntryRequest):
_json_body = body.to_dict()
_kwargs["json"] = _json_body
headers["Content-Type"] = "application/json"
if isinstance(body, WritableJournalEntryRequest):
_files_body = body.to_multipart()
_kwargs["files"] = _files_body
headers["Content-Type"] = "multipart/form-data"
# ...As you can see, both if-statement's conditions will resolve to True, therefore only the last body type will be used.
Desired Behavior
The body-type should be part of the generated class name to avoid such ambiguities.
Or an if/elseif/else should be used in the template (which would result in the first one being applied ONLY).
OpenAPI Spec File
The OpenAPI spec is from Netbox, but here is the relevant snippet:
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/WritableJournalEntryRequest"
}
},
"multipart/form-data": {
"schema": {
"$ref": "#/components/schemas/WritableJournalEntryRequest"
}
}
},
"required": true
},I worked around this by using a custom template for endpoint_module.py.jinja. Gist, Patch:
$ diff /tmp/orig/endpoint_module.py.jinja custom-templates/endpoint_module.py.jinja
21c21
< {{ arguments(endpoint, include_client=False) | indent(4) }}
---
> {{ arguments(endpoint, include_client=True) | indent(4) }}
48a49
> content_type = client._headers.get("Content-Type") or client._headers.get("content-type")
50c51
< if isinstance(body, {{body.prop.get_type_string() }}):
---
> if isinstance(body, {{body.prop.get_type_string() }}) and (content_type is None or content_type == "{{ body.content_type }}"):
108c109
< {{ kwargs(endpoint, include_client=False) }}
---
> {{ kwargs(endpoint, include_client=True) }}
134c135
< {{ kwargs(endpoint, include_client=False) }}
---
> {{ kwargs(endpoint, include_client=True) }}
With this custom template in a location like custom-templates/endpoint_module.py.jinja, openapi-python-client generate --custom-template-path=custom-templates generates the patched code. Using the patch requires setting the content-type header to the desired type when creating a Client object.
I suspect this is not a proper fix, which probably needs a better way of handling differing body types with the same class names. I'm not really knowledgable enough about this codebase to do that, just sharing in case it helps someone else.