0
0
FastapiHow-ToBeginner · 4 min read

How to Use Alias in Pydantic Model in FastAPI

In FastAPI, you can use the alias parameter in Pydantic model fields to map incoming JSON keys to different Python attribute names. This allows you to accept data with keys that don't match your Python variable names while keeping your code clean and readable.
📐

Syntax

Use the Field function from Pydantic to set an alias for a model attribute. This alias is the key name expected in the input data (like JSON), while the attribute name is used in your Python code.

  • attribute_name: The Python variable name.
  • Field(..., alias='json_key'): Defines the JSON key name.
python
from pydantic import BaseModel, Field

class MyModel(BaseModel):
    attribute_name: str = Field(..., alias='json_key')
💻

Example

This example shows a FastAPI app where the Pydantic model uses an alias to accept a JSON key userName but uses username in Python code. The alias allows the API to receive data with different key names than the Python attributes.

python
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class User(BaseModel):
    username: str = Field(..., alias='userName')

@app.post('/users/')
async def create_user(user: User):
    return {"received_username": user.username}
Output
POST /users/ with JSON {"userName": "alice"} returns {"received_username": "alice"}
⚠️

Common Pitfalls

One common mistake is forgetting to enable allow_population_by_field_name=True in the model config if you want to use the Python attribute names when creating model instances manually. Also, if you don't use the alias in input JSON, validation will fail.

Another pitfall is expecting the alias to change the output keys by default; you must set by_alias=True when exporting data to use aliases in output.

python
from pydantic import BaseModel, Field

class User(BaseModel):
    username: str = Field(..., alias='userName')

    class Config:
        allow_population_by_field_name = True

# Correct: creating instance with alias key works only if allow_population_by_field_name=True
# user = User(userName='alice')

# Output with alias
user = User(username='alice')
print(user.dict(by_alias=True))  # {'userName': 'alice'}

# Output without alias
print(user.dict())  # {'username': 'alice'}
Output
{'userName': 'alice'} {'username': 'alice'}
📊

Quick Reference

FeatureDescriptionUsage
aliasMaps JSON key to Python attributeField(..., alias='json_key')
allow_population_by_field_nameAllows creating model with Python namesclass Config: allow_population_by_field_name = True
by_aliasOutputs dict with alias keysmodel.dict(by_alias=True)

Key Takeaways

Use Field(..., alias='json_key') to map JSON keys to Python attributes in Pydantic models.
Set allow_population_by_field_name=True in Config to create models using Python attribute names.
Use model.dict(by_alias=True) to output data with alias keys instead of Python attribute names.
Aliases help keep API input/output flexible without changing your Python code style.
Always match input JSON keys to aliases to avoid validation errors.