How to Use Alias in Pydantic Model in FastAPI
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.
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.
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}
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.
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'}
Quick Reference
| Feature | Description | Usage |
|---|---|---|
| alias | Maps JSON key to Python attribute | Field(..., alias='json_key') |
| allow_population_by_field_name | Allows creating model with Python names | class Config: allow_population_by_field_name = True |
| by_alias | Outputs dict with alias keys | model.dict(by_alias=True) |