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

Fix issue with fastapi generator converting all fields to snake_case #12261

Merged
merged 2 commits into from
May 9, 2022

Conversation

RoryDungan
Copy link
Contributor

I noticed that the Python-FastAPI generator converts all model field names to snake_case to match Python convention. While this is desireable from a code-style perspective, it breaks any API using a different convention for field names since it also affects the names of fields that get serialised to JSON.

FastAPI uses Pydantic for its model classes, which supports setting an alias value in order to deserialise a different name to what is used for the Python class, so I modified the generator to use this. Be default it will always be used during deserialisation but only during serialisation if the by_alias=True option is specified. Luckily, FastAPI includes an option we can set on endpoints that will use this for data returned by the endpoint, response_model_by_alias=True.

I've enabled this everywhere because there's no harm in using it if the alias is the same as the name and it seemed like adding logic to specifically detect camelCase field names would overcomplicate things, plus this could potentially be useful if you have an OpenAPI spec that includes a field name that is a reserved word in Python, although I haven't tested it in that case.

Here's an example of some code before and after the change:

# before:
class RenderClip(BaseModel):
    """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).

    Do not edit the class manually.

    RenderClip - a model defined in OpenAPI

        focused_player_actor_id: The focused_player_actor_id of this RenderClip.
        time_range: The time_range of this RenderClip.
        ingredients: The ingredients of this RenderClip.
        output_length: The output_length of this RenderClip [Optional].
    """

    focused_player_actor_id: str
    time_range: GameTimeRange
    ingredients: List[Ingredient]
    output_length: Optional[float] = None

# after:
class RenderClip(BaseModel):
    """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).

    Do not edit the class manually.

    RenderClip - a model defined in OpenAPI

        focused_player_actor_id: The focused_player_actor_id of this RenderClip.
        time_range: The time_range of this RenderClip.
        ingredients: The ingredients of this RenderClip.
        output_length: The output_length of this RenderClip [Optional].
    """

    focused_player_actor_id: str = Field(alias="focusedPlayerActorId")
    time_range: GameTimeRange = Field(alias="timeRange")
    ingredients: List[Ingredient] = Field(alias="ingredients")
    output_length: Optional[float] = Field(alias="outputLength", default=None)

This may also fix #11604 since it allows serializing/deserializing models with names in camelCase without requiring any additional options in the generator.

I've made this change on top of 5.4.x because that's what our team is using so if this could be included in a patch release of 5.4.x that would be ideal, although I have also tested on master and it works so if you think it would be more appropriate to commit there I'm happy to rebase.

PR checklist

  • [✓] Read the contribution guidelines.
  • [✓] Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • [✓] Run the following to build the project and update samples:
    ./mvnw clean package 
    ./bin/generate-samples.sh
    ./bin/utils/export_docs_generators.sh
    
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    For Windows users, please run the script in Git BASH.
  • [✓] If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.
    This change applies to the Python-FastAPI server generator @taxpon @frol @mbohlool @cbornet @kenjones-cisco @tomplus @arun-nalla @spacether

@RoryDungan
Copy link
Contributor Author

The build failed with this error:

Cannot run program "gradle" (in directory "/home/circleci/OpenAPITools/openapi-generator/samples/client/petstore/groovy"): error=2, No such file or directory

I can't see how this is related to my change, so maybe it's an existing flakiness or an existing issue on the 5.4.x branch?

@spacether
Copy link
Contributor

Can you please rebase on master? We don't do later releases of old builds like 5.4.x

@RoryDungan RoryDungan changed the base branch from 5.4.x to master May 2, 2022 01:44
@RoryDungan
Copy link
Contributor Author

@spacether I've rebased on master now

@wing328
Copy link
Member

wing328 commented May 9, 2022

@wing328 wing328 merged commit fd5ad7f into OpenAPITools:master May 9, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Question] [python-fastapi] How to set _spec_property_naming = True via command line
4 participants