Python · Pydantic API models
Pydantic camelCase ↔ snake_case aliases
Keep Python model fields snake_case while accepting or emitting a different JSON naming convention through model aliases.
Use alias_generator for one external convention
from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_camel
class UserProfile(BaseModel):
model_config = ConfigDict(
alias_generator=to_camel,
validate_by_alias=True,
validate_by_name=True,
)
first_name: str
created_at: str
profile = UserProfile.model_validate({
"firstName": "Ada",
"createdAt": "2026-09-12",
})
print(profile.first_name)
print(profile.model_dump(by_alias=True))
# {'firstName': 'Ada', 'createdAt': '2026-09-12'}Pydantic provides built-in alias generators such as to_camel and to_snake, and model_dump(by_alias=True) emits external names.
Use AliasGenerator when validation and serialization differ
from pydantic import AliasGenerator, BaseModel, ConfigDict
from pydantic.alias_generators import to_camel, to_snake
class UserProfile(BaseModel):
model_config = ConfigDict(
alias_generator=AliasGenerator(
validation_alias=to_camel,
serialization_alias=to_snake,
),
validate_by_alias=True,
)
first_name: str
created_at: str
profile = UserProfile.model_validate({
"firstName": "Ada",
"createdAt": "2026-09-12",
})
print(profile.model_dump(by_alias=True))
# {'first_name': 'Ada', 'created_at': '2026-09-12'}AliasGenerator can configure validation_alias and serialization_alias separately when incoming and outgoing names follow different conventions.
Production considerations
- Field-level aliases can take precedence over generated aliases, so document and test explicit exceptions.
- Prefer model aliases when Pydantic already validates the payload; recursive dictionary conversion is better for unmodeled JSON.
- Use model_dump(by_alias=True) when serialized JSON needs generated external field names.
- Keep naming policy at the model or serialization boundary instead of leaking external API casing into Python business logic.
Test the JSON boundary online
Use the browser tool to test nested objects, arrays, excluded keys, stop paths, semantic prefixes, collision handling, and a key-only diff before you copy the same convention into an application.
Drop a .json file here or choose one from your device
Files are read only in your browser. Maximum file size: 5 MB.
{
"userProfile": {
"firstName": "Ada",
"createdAt": "2026-09-12"
}
}Parsing, file reading, formatting, and key conversion run locally in your browser. JSON input is not sent to a conversion server.