Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG][python-fastapi] fieldNames with reserved words are turned into private attributes in pydantic models #20030

Closed
5 of 6 tasks
andlien opened this issue Nov 5, 2024 · 1 comment · Fixed by #20035
Closed
5 of 6 tasks

Comments

@andlien
Copy link
Contributor

andlien commented Nov 5, 2024

Bug Report Checklist

  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator (example)?
  • Have you tested with the latest master to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description

When generating pydantic models with the python-fastapi generator, reserved words are escaped by prepending an underscore. This results in pydantic treating the fields as a private attribute which is ignored in validation and (de)serialization. Furthermore, as of Pydantic v2.1.0, you receive a NameError if trying to use the Field function with a private attribute.

openapi-generator version

latest master

OpenAPI declaration file content or url

Sample OpenApi spec

Generating models for this spec results in the following model

class TestDTO(BaseModel):
    _self: StrictStr = Field(alias="self")
    foo: StrictStr
    bar: StrictStr
    __properties: ClassVar[List[str]] = ["self", "foo", "bar"]
Generation Details

No special config

Steps to reproduce

openapi-generator generate -i sample.json -g python-fastapi -o /tmp/test/

Related issues/PRs

I have not found anything related

Suggest a fix

The escaping is currently performed in AbstractPythonCodegen.escapeReservedWord(). The python client generator also generates pydantic models, but it's overriding the method prepending "var_" istead. I assume copying this implementation in PythonFastAPIServerCodegen.java would fix the issue.

@wing328
Copy link
Member

wing328 commented Nov 6, 2024

thanks for reporting the issue

as a workaround, please use the name mapping option: https://github.com/openapitools/openapi-generator/blob/master/docs/customization.md#name-mapping

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants