skip to content

In Pydantic 2, why does model_dump() emit snake_case keys for a model whose fields have camelCase aliases, and how do you publish camelCase JSON?

level: middleimportance: should knowfreq 58%

answer

  1. aliases are asymmetric by default
  2. validation uses them, dumping does not
  3. a per-call flag or a config key
  4. nested models and the schema

basics

~10 s

Pydantic 2 validates by alias by default but serializes by field name: by_alias is False unless you pass by_alias=True on the dump call or set serialize_by_alias=True in model_config, available since 2.11.

solid answer

~40 s

Aliases in Pydantic 2 are asymmetric. On input, `validate_by_alias` defaults to `True`, so a payload with `orderId` populates `order_id`. On output, `by_alias` defaults to `False` and the model setting `serialize_by_alias` defaults to `False`, so `model_dump()` and `model_dump_json()` use the Python field names. To publish camelCase I either pass `by_alias=True` on the call, which applies to nested models too, or set `ConfigDict(serialize_by_alias=True)`, added in 2.11, on a shared base class so every event model inherits it. A `serialization_alias` outranks `alias` on the way out, and a field with only a `validation_alias` still dumps under its name. I also watch the JSON Schema: `model_json_schema()` uses aliases by default, so a default dump disagrees with the schema you hand consumers.

code

python · 24 lines
python
from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_camel


class EventBase(BaseModel):
    model_config = ConfigDict(alias_generator=to_camel, serialize_by_alias=True)


class Address(EventBase):
    postal_code: str


class OrderShipped(EventBase):
    order_id: str
    ship_to: Address


evt = OrderShipped.model_validate({'orderId': 'o-17', 'shipTo': {'postalCode': '10115'}})

print(evt.model_dump_json())
#> {"orderId":"o-17","shipTo":{"postalCode":"10115"}}

print(evt.model_dump_json(by_alias=False))
#> {"order_id":"o-17","ship_to":{"postal_code":"10115"}}

go deeper

for a junior

Recall that aliases are used for input by default but not for output, and that by_alias=True on the dump call switches the keys to the aliases.

for a middle

Explain the defaults on both sides, the serialize_by_alias setting added in 2.11, and how serialization_alias outranks alias when dumping.

for a senior

Show the traps: nested models without the setting, validation-only aliases, and a JSON Schema that uses aliases while the default dump does not, breaking consumers.

for a principal

Decide where alias policy lives, a shared event base class or one publishing helper, so camelCase output does not depend on every engineer remembering a flag.

## Aliases point in two directions A Pydantic 2 field can carry up to three alias settings, declared on `Field()` or generated for every field by an `alias_generator` such as `to_camel` (declaring them is a matter for the material on models and fields): - `alias` applies to both validation and serialization; - `validation_alias` applies only when reading input; - `serialization_alias` applies only when writing output, and it **outranks** `alias` there. Declaring an alias does not by itself change what a dump emits. The defaults are deliberately different on the two sides: | Direction | Setting | Default | |---|---|---| | Input | `ConfigDict(validate_by_alias=...)` | `True`, so the alias is accepted | | Input | `ConfigDict(validate_by_name=...)` | `False`, so the field name is refused | | Output | `model_dump(by_alias=...)`, `model_dump_json(by_alias=...)` | not passed, which falls back to the model setting | | Output | `ConfigDict(serialize_by_alias=...)` | `False`, so field names are used | | Schema | `model_json_schema(by_alias=...)` | `True`, so aliases are used | So a model with `alias_generator=to_camel` happily validates `{"orderId": ...}` and then dumps `{"order_id": ...}`. Pydantic's own documentation calls this inconsistent and says the serialization default is expected to change to `True` in version 3. ## Two ways to emit the alias 1. **Per call:** `evt.model_dump_json(by_alias=True)`. The runtime flag reaches every nested model in that dump, which makes it the reliable choice at a single publishing point. 2. **Per model:** `model_config = ConfigDict(serialize_by_alias=True)`, introduced in 2.11. It is a model-level setting, so a nested model that does not carry it dumps its own fields by name. Put it on a **shared base class** that every event model inherits, and the whole tree agrees. A runtime `by_alias=False` still overrides it for one call. ## Details that bite - A field with only `validation_alias` is dumped under its **field name** even with `by_alias=True`, because no serialization alias exists. - When `alias` and `serialization_alias` are both set, output uses `serialization_alias`. This is how you accept one spelling and emit another. - A `@computed_field` takes its own `alias` argument, which the dump uses under the same `by_alias` rules. - The consuming side may need `validate_by_name=True` as well if it must accept payloads written both ways during a migration. - `model_json_schema()` defaults to `by_alias=True`. If you publish that schema as the contract but dump with the defaults, the schema says `orderId` and the payload says `order_id`. Keep schema generation and dumping on the same alias setting. ## A worked shape for camelCase events For an event published to a service that expects camelCase: - define `EventBase(BaseModel)` with `model_config = ConfigDict(alias_generator=to_camel, serialize_by_alias=True)`; - derive every event and every nested payload model from it; - publish with `evt.model_dump_json()`, and generate the contract with `model_json_schema(mode='serialization')`, which already uses aliases. Because `to_camel` generates an `alias`, the same base class accepts camelCase input too, so an event round-trips through `model_validate_json()` unchanged. If you instead need snake_case input and camelCase output, generate only serialization aliases with an `AliasGenerator(serialization_alias=to_camel)`. ## Diagnosing a key mismatch When a consumer reports snake_case keys, or a mix of both styles, work through it in this order: 1. **Dump one instance by hand** with the exact call the publisher uses and compare its keys with the schema you published. 2. **Check the call:** is `by_alias=True` passed, or explicitly `by_alias=False`, which overrides any config? 3. **Check every nested model's config:** a nested model that does not inherit `serialize_by_alias=True` dumps its own keys by name, which produces exactly the mixed output. 4. **Check the kind of alias:** a `validation_alias` alone never reaches the output. 5. **Check other dump paths:** a list of events dumped through a `TypeAdapter` needs the same `by_alias=True` on `dump_json()`. ## Why the default matters to a team The asymmetry is easy to miss in review: tests that build models from camelCase fixtures pass, and the bug appears only when another service parses your snake_case output. A base class with the setting, or one helper that always passes `by_alias=True`, removes the decision from every individual call site.

  • You set serialize_by_alias=True on the event model, but a nested address still dumps snake_case keys. Why?
    `serialize_by_alias` is a model-level setting, and the nested model has its own config without it, so it dumps its fields by name. Either put the setting on a base class both models inherit, or pass `by_alias=True` at the call, which applies to every nested model in that dump.
  • How do you accept snake_case from one producer but always emit camelCase?
    Give the fields serialization aliases only, for example `Field(serialization_alias='orderId')` or `AliasGenerator(serialization_alias=to_camel)` in `alias_generator`, and dump by alias. Validation then reads field names, because there is no validation alias, while every dump by alias writes camelCase.

  • Declaring an alias makes model_dump() use it automatically
  • validate_by_alias=True also makes the model serialize by alias
  • serialize_by_alias on the outer model also covers nested models with their own config
  • A field with only validation_alias dumps under that alias with by_alias=True
  • model_json_schema() uses field names unless you pass by_alias=True