mrlucasrib
mrlucasrib

Reputation: 220

The alias field of the Pydantic Model schema is by default in swagger instead of the original field

I need to receive data from an external platform (cognito) that uses PascalCase, and the Pydantic model supports this through field aliases, adding an alias_generator = to_camel in the settings I make all fields have a PascalCase alias corresponding

In this way, the model:

class AuthenticationResult(BaseModel):
    access_token: str
    expires_in: int
    token_type: str
    refresh_token: str
    id_token: str
    
    class Config:
        alias_generator = to_camel
        allow_population_by_field_name = True

it can receive the following dictionary without the slightest problem:

data = {
  "AccessToken": "myToken",
  "ExpiresIn": 0,
  "TokenType": "string",
  "RefreshToken": "string",
  "IdToken": "string"
}
auth_data = AuthenticationResult(**data)

print(auth_data.access_token)
# Output: myToken

However, in the application's Swagger documentation it is also in PascalCase format, but it must return in snake_case format, which is strange, since by_alias is False by default. Here's the format:

Swagger Printscreen

I need it to be in snake_case format to send it to the client. How can I do this, so that it continues to accept being built using a PascalCase dictionary

Upvotes: 3

Views: 1405

Answers (1)

Samuel Colvin
Samuel Colvin

Reputation: 13329

Might be easiest to create a sub model inheriting from your main model to set the alias generator on, then user that model for validation and the first one to generate the schema.

Upvotes: 2

Related Questions