Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Pydantic Aliases and Serialization

Learn how Pydantic aliases affect serialization and how to use by_alias and populate_by_name to control field names in model_dump and JSON output.

~5 min readPython
#pydantic#aliases#serialization#data validation
Illustration of a Pydantic model with field names mapped to alias names during serialization, showing arrows from snake_case to camelCase and a JSON output.

When you define a Pydantic model, field names are the default keys for both validation and serialization. But real-world data often arrives with different names—snake_case in Python, camelCase in JSON APIs. Pydantic aliases solve that mismatch, but they also interact with serialization in ways you need to control explicitly. This article explains how Pydantic aliases and serialization interact, and how to get the field names you expect in your output.

What Aliases Do in Pydantic Models

An alias is an alternative name for a field, used primarily during validation (parsing input) and optionally during serialization (producing output). You define an alias with the alias parameter in Field:

python
from pydantic import BaseModel, Field class User(BaseModel): user_id: int = Field(alias="userId") full_name: str = Field(alias="fullName")

Here, the model expects incoming data to use userId and fullName as keys. If you try to validate a dict with user_id, it will fail unless you also set populate_by_name (explained later). The alias exists to match an external contract, like a JSON API that uses camelCase, while the Python attribute remains snake_case.

Default Serialization Uses Field Names

In Pydantic v2, by default, serialization uses the Python field names, not the aliases. This is a common source of confusion. Consider the model above and this instance:

python
user = User(userId=1, fullName="Alice") print(user.model_dump())

Output:

python
{'user_id': 1, 'full_name': 'Alice'}

Even though the input used aliases, model_dump() returns the field names. This is intentional: aliases are meant for external representation, but the internal Python representation uses the attribute names. If you need the output to match the alias names, you must explicitly request it.

Serializing with Aliases: by_alias=True

To serialize using aliases, pass by_alias=True to model_dump() or model_dump_json():

python
print(user.model_dump(by_alias=True)) print(user.model_dump_json(by_alias=True))

Output:

python
{'userId': 1, 'fullName': 'Alice'}
json
{"userId":1,"fullName":"Alice"}

The by_alias flag applies to both dict and JSON output. This is the key mechanism for producing serialized data that matches your external schema.

Controlling Alias Usage in Different Output Formats

Pydantic v2 provides model_dump() and model_dump_json(); v1 uses dict() and json(). The by_alias parameter exists in both, so the principle is the same. The table below summarizes the default behavior, assuming no model-config override:

MethodOutput keys
model_dump()Field names
model_dump(by_alias=True)Aliases
model_dump_json()Field names (JSON)
model_dump_json(by_alias=True)Aliases (JSON)

In Pydantic v2, you can also set model_config = ConfigDict(serialize_by_alias=True) to make serialization use aliases by default. That forces aliases for all serialization on the model, which may not be desirable if you need both representations in different contexts. Explicit per-call control is usually clearer.

Validation with Aliases: populate_by_name

In Pydantic v2, validation uses the alias only by default. If you want to accept both the alias and the field name, set model_config = ConfigDict(populate_by_name=True):

python
from pydantic import BaseModel, Field, ConfigDict class User(BaseModel): model_config = ConfigDict(populate_by_name=True) user_id: int = Field(alias="userId") full_name: str = Field(alias="fullName") # Both work now: user1 = User(userId=1, fullName="Alice") user2 = User(user_id=2, full_name="Bob")

This is useful when you control both the external API and the internal code, and you want to avoid forcing callers to use the alias. However, it adds ambiguity: if a field name and alias differ, both are accepted, which can hide typos. Use it deliberately. In Pydantic v1, the equivalent config option was allow_population_by_field_name = True.

Common Pitfalls and How to Avoid Them

Forgetting by_alias in Serialization

The most frequent mistake is expecting aliases in output without passing by_alias=True. Always check whether your API contract requires aliases in responses. If it does, make sure every serialization call includes the flag, or consider a helper function.

Alias Conflicts with Field Names

When an alias collides with another field's name or alias, Pydantic v2 raises an error at model definition time. This is good, but it can occur when aliases are generated from field names with a pattern that collides. For example, if you have fields user_id and userId, and you generate aliases that strip underscores, you get duplicates. Use a consistent naming strategy and test your models.

Nested Models and Aliases

Aliases apply recursively when you serialize a model that contains other models. If a child model has aliases, by_alias=True will use them in the nested output as well. The flag applies to the whole serialization tree, so you cannot turn it on for some nested models and off for others in a single model_dump() call.

Using alias_generator for Consistency

For large models, manually specifying aliases is repetitive. Pydantic provides alias_generator to derive aliases from field names automatically:

python
from pydantic import BaseModel, ConfigDict def to_camel(s: str) -> str: parts = s.split('_') return parts[0] + ''.join(p.title() for p in parts[1:]) class User(BaseModel): model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True) user_id: int full_name: str

Now user_id becomes userId and full_name becomes fullName automatically. This reduces boilerplate and ensures a uniform external naming convention.

Choosing Between Field Names and Aliases in API Contracts

Aliases let you keep Pythonic field names internally while exposing a different schema externally. This is valuable when you cannot change an existing API or when you want to decouple internal code from external wire format. However, aliases add a layer of indirection that increases cognitive load. If you control both ends, consider whether a simple rename of the Python field is better. For example, if your API uses camelCase and your code is new, you could just name the fields userId and fullName and skip aliases entirely. But if you have existing Python code that uses snake_case, or if you need to support multiple external schemas, aliases are the right tool.

When using aliases, be explicit about when by_alias is needed. Define a clear policy: for example, always use by_alias=True when serializing to external responses, and never when dumping internal state for debugging. This consistency prevents subtle bugs where a response accidentally uses field names instead of aliases, breaking clients that expect the external contract.

Finally, remember that aliases affect validation as well as serialization. The populate_by_name setting gives you flexibility, but it also means input data can contain either name. Decide whether you want to accept both or enforce a single canonical input format. The choice depends on how strict your API needs to be and how much you trust your clients to follow the spec.

Pydantic aliases are a powerful feature, but they require deliberate handling during serialization. By understanding the default behavior and using by_alias and populate_by_name intentionally, you can maintain clean internal models and consistent external APIs without surprises.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.