Using AliasChoices and AliasPath in Pydantic

When building APIs or data pipelines, sometimes you don't have control over the shape of the input data. That’s where AliasChoices and AliasPath from Pydantic v2 can really shine.

Let’s look at two quick and powerful tools that make your models way more flexible.


🎭 AliasChoices: Accept multiple names for the same field

Say you have a Person model, but the incoming JSON can have the name under "name", "nome", or "full_name" depending on the source.

pythonCopyEditfrom pydantic import BaseModel, AliasChoices

class Person(BaseModel):
    name: str = AliasChoices("name", "nome", "full_name")

Now all these payloads will work just fine:

pythonCopyEditPerson(**{"name": "Alice"})
Person(**{"nome": "Alice"})
Person(**{"full_name": "Alice"})

In all cases, the name field in your model will be set to "Alice".


🧬 AliasPath: Dig into nested structures

Imagine you receive a deeply nested JSON, and you only want one specific value. With AliasPath, you can extract it directly.

pythonCopyEditfrom pydantic import BaseModel, AliasPath

class User(BaseModel):
    email: str = AliasPath("data", "profile", "contact", "email")

Given the input:

jsonCopyEdit{
  "data": {
    "profile": {
      "contact": {
        "email": "user@example.com"
      }
    }
  }
}

Pydantic will fill in email = "user@example.com" just like magic ✨


🔀 You can even mix both

Here’s a real-world example combining both tools:

pythonCopyEditfrom pydantic import BaseModel, AliasChoices, AliasPath

class Payload(BaseModel):
    level: int = AliasChoices(
        "lvl",
        "level",
        AliasPath("settings", "access", "level")
    )

This model will accept:

pythonCopyEditPayload(**{"lvl": 5})
Payload(**{"level": 5})
Payload(**{"settings": {"access": {"level": 5}}})

🧩 Why this matters

With AliasChoices and AliasPath, your models become more robust, user-friendly, and interoperable. You no longer need to pre-process data to normalize field names — Pydantic takes care of it.

Whether you're consuming third-party APIs, loading legacy data, or just keeping your inputs flexible, these two features can save you a lot of boilerplate.

0
Subscribe to my newsletter

Read articles from Pedro Buzzi Filho directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pedro Buzzi Filho
Pedro Buzzi Filho