skip to content

In Pydantic 2, how do you make an order model accept a partner's camelCase keys while your code keeps snake_case field names?

level: middleimportance: should knowfreq 60%

answer

  1. names inside, other keys outside
  2. one direction or both
  3. generator in model_config
  4. aliases win over names by default

basics

~10 s

Give fields aliases: Field(alias=...) or validation_alias per field, or alias_generator=to_camel in model_config for all of them. Pydantic 2 then validates by alias only, so add validate_by_name=True if code must also construct with snake_case names.

solid answer

~40 s

An **alias** is the key Pydantic looks for in input instead of the attribute name. `Field(alias='customerId')` applies to validation and to dumping by alias; `validation_alias` applies only on the way in and also accepts `AliasChoices` (several accepted keys, first wins) and `AliasPath` (a nested lookup); `serialization_alias` applies only on the way out. For a whole model, set `model_config = ConfigDict(alias_generator=to_camel)` from `pydantic.alias_generators`; an explicit field alias still beats the generated one. By default Pydantic validates **by alias only** (`validate_by_alias=True`, `validate_by_name=False`), so `Order(customer_id=42)` fails with `missing`. Set `validate_by_name=True` (2.11 and later; formerly `populate_by_name`) or pass `by_name=True` per call. Config does not reach nested models, so share it through a base class.

code

python · 28 lines
python
from pydantic import AliasChoices, BaseModel, ConfigDict, Field
from pydantic.alias_generators import to_camel


class PartnerModel(BaseModel):
    model_config = ConfigDict(alias_generator=to_camel, validate_by_name=True)


class LineItem(PartnerModel):
    sku: str
    unit_price: float


class Order(PartnerModel):
    order_id: str = Field(validation_alias=AliasChoices('orderRef', 'orderId'))
    customer_id: int
    line_items: list[LineItem]


order = Order.model_validate({
    'orderRef': 'A-17',
    'customerId': 42,
    'lineItems': [{'sku': 'SKU-1', 'unitPrice': 9.5}],
})
print(order.line_items[0].unit_price)
#> 9.5
print(Order(order_id='A-18', customer_id=7, line_items=[]).customer_id)
#> 7

go deeper

for a junior

Recall that an alias is the input key Pydantic reads instead of the attribute name, and that alias_generator with to_camel aliases every field.

for a middle

Explain alias versus validation_alias versus serialization_alias, AliasChoices and AliasPath, and why construction by field name fails until validate_by_name is set.

for a senior

Diagnose nested models ignoring the camelCase generator because configuration stops at each model, and fix it with a shared base class and a real-payload test.

for a principal

Decide whether partner-facing models get a separate base class with their own naming policy, and how renamed partner keys are retired over time.

## Why aliases exist Python code conventionally uses **snake_case** attribute names, while many JSON producers send **camelCase** keys: `customerId`, `lineItems`, `unitPrice`. An **alias** is an alternative key that Pydantic uses when reading input (and, if asked, when writing output), so the model's attributes can keep Pythonic names while the payload keeps the partner's. ## The four ways to declare an alias | Mechanism | Applies to | Accepts | |---|---|---| | `Field(alias='customerId')` | validation, and dumping by alias | a string | | `Field(validation_alias=...)` | validation only | a string, `AliasChoices`, `AliasPath` | | `Field(serialization_alias=...)` | dumping by alias only | a string | | `ConfigDict(alias_generator=...)` | every field of that model | a callable or an `AliasGenerator` | Two helpers make `validation_alias` more flexible: - **`AliasChoices('orderRef', 'orderId')`** accepts any of several keys. When the input contains more than one, the earlier choice in the list wins. - **`AliasPath('contact', 'address')`** reads a value from a nested location, including list indexes such as `AliasPath('names', 0)`. For camelCase across a whole model, use the built-in generator: `from pydantic.alias_generators import to_camel`, then `model_config = ConfigDict(alias_generator=to_camel)`. Pydantic also ships `to_pascal` and `to_snake`. An `AliasGenerator(validation_alias=..., serialization_alias=...)` lets input and output use different conventions. ## Reaching into a nested payload with `AliasPath` Partners do not always nest data the way your model does. Suppose an order arrives as `{"customer": {"id": 42, "tier": "gold"}, ...}` but your `Order` wants a flat `customer_id: int`. Instead of declaring a throwaway `Customer` model, write: - `customer_id: int = Field(validation_alias=AliasPath('customer', 'id'))` Pydantic walks the input to `customer`, then `id`, and validates what it finds as an `int`. Combine it with `AliasChoices` when the same value may arrive flat in newer messages and nested in older ones: `AliasChoices('customerId', AliasPath('customer', 'id'))`. Because these are validation aliases, they shape only what the model reads, never what it writes. ## Precedence between an explicit alias and the generator When a field has its own alias and the model has a generator, the **explicit alias wins** by default. `alias_priority` changes that per field: 1. `alias_priority=2`: the explicit alias is never overridden. 2. `alias_priority=1`: the generator overrides it. 3. Not set: an explicit alias is kept; a field without one gets the generated alias. ## The default that surprises people: names stop working Once a field has an alias, Pydantic 2 by default validates **by alias only**. The two settings are: - `validate_by_alias`: `True` by default. - `validate_by_name`: `False` by default. So with `customer_id: int = Field(alias='customerId')`, the call `Order(customer_id=42)` does not set the field. The `customer_id` key is treated as unknown (ignored under the default `extra='ignore'`), and validation reports `customerId` as `missing`. Tests and internal code that build models by attribute name break in exactly this way. The fixes: - Set `validate_by_name=True` in `model_config` so both the alias and the name are accepted. This setting arrived in **2.11**; the older `populate_by_name=True` still works but the documentation no longer recommends it, and version 1's name for it was `allow_population_by_field_name`. - Or pass per call: `Order.model_validate(data, by_alias=True, by_name=True)`. - You cannot turn both `validate_by_alias` and `validate_by_name` off; Pydantic raises a usage error. ## Configuration stops at each model An alias generator lives in one model's `model_config`, and Pydantic gives every model its own **configuration boundary**: a generator on `Order` does not rename the keys of a nested `LineItem`. The partner's `lineItems[].unitPrice` would then fail. The tidy fix is a small base class, for example `PartnerModel(BaseModel)` carrying `alias_generator=to_camel` and `validate_by_name=True`, which every partner-facing model inherits; subclass configuration is merged with the parent's. ## Output is a separate decision Aliases are used on input by default but **not** on output: dumping uses attribute names unless you ask for aliases. How to emit camelCase JSON again belongs with the material on dumping models, and is worth a separate look before you rely on a round trip. ## Checklist for a partner-facing model - Put `alias_generator=to_camel` and `validate_by_name=True` on a shared base class. - Use `validation_alias=AliasChoices(...)` where the partner has used more than one key over time. - Keep explicit `alias=` for the odd key that the generator would get wrong. - Write at least one test that validates a real partner payload, nested items included.

  • In Pydantic 2, a partner renamed `orderId` to `orderRef` but old messages are still replayed. How do you accept both?
    Declare `order_id: str = Field(validation_alias=AliasChoices('orderRef', 'orderId'))`. Pydantic tries the choices in order and uses the first key present, so a payload carrying both resolves to `orderRef`. Because it is a validation alias, it does not change the key used when dumping by alias.
  • In Pydantic 2, why might `validate_by_alias=False` on its own be a surprise?
    Setting it to `False` turns off alias lookup, and since both cannot be off, Pydantic implicitly sets `validate_by_name=True`. The model then accepts only attribute names, so the partner's camelCase payload fails. To accept both forms, keep `validate_by_alias=True` and add `validate_by_name=True`.

  • With an alias set, the field name is still accepted by default.
  • An alias generator on the outer model also renames nested models' keys.
  • validation_alias changes the key written when dumping by alias.
  • populate_by_name is the recommended spelling on Pydantic 2.11 and later.
  • A generated alias always overrides an explicit Field alias.