Emit API-compatible keys
An API contract requires camelCase or another external naming convention.
Pydantic · Module
model_dump(by_alias=True) serializes a Pydantic model to a dictionary using configured field aliases as keys. Leave it false or unset to use Python attribute names.
model_dump(by_alias=True) returns the model as a dictionary while using configured field aliases as the output keys. With the default False, serialization uses the model's attribute names; aliases can come from Field definitions or an alias generator.
model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False) -> dict[str, Any]| Name | Type | Description |
|---|---|---|
by_alias | bool | None | Whether to use field aliases as dictionary keys during serialization; defaults to False. |
A dictionary representation of the model, using aliases when by_alias=True.
from pydantic import BaseModel, Field
class User(BaseModel):
user_id: int = Field(alias='userId')
user = User(userId=7)
print(user.model_dump(by_alias=True))
# {'userId': 7}Use by_alias=True to serialize fields with their configured aliases instead of their Python attribute names.
An API contract requires camelCase or another external naming convention.
A model uses Field aliases for database, JSON, or wire-format names.
Many fields follow a naming convention defined by an alias generator.
model_dump(by_alias=True) serializes a model to a dictionary and uses each field's configured alias as the key. If by_alias is omitted or false, the normal attribute names are used.
Follow-up: How can aliases be applied consistently across a model? Define an alias_generator in model configuration, then call model_dump(by_alias=True) to emit the generated aliases.
The setting affects the serialized dictionary keys, not the model's Python attributes. A field declared with an alias such as userId remains accessible through its Python attribute name inside the model.
Follow-up: Does by_alias=True make alias-based construction valid? No; input behavior is controlled separately by validation configuration such as validate_by_alias.
Aliases can be declared per field with Field(alias=...) or generated through model configuration. Dumping with by_alias=True makes those aliases appear in the output dictionary.
Follow-up: What output would an alias generator produce? It transforms configured field names according to the generator, and the transformed names are emitted when aliases are requested.
BaseModel.model_dumpField(alias=...)ConfigDict(alias_generator=...)validate_by_aliasvalidate_by_name