How to Use Config Class in Pydantic with FastAPI
In FastAPI, use the
Config class inside a Pydantic model to customize behavior like enabling orm_mode for ORM compatibility or setting JSON encoders. Define a nested Config class with attributes inside your model to control validation and serialization.Syntax
The Config class is a nested class inside a Pydantic model. It lets you set options that change how the model behaves during validation and serialization.
- orm_mode: Allows the model to read data from ORM objects.
- json_encoders: Customize how certain types are converted to JSON.
- any_other_option: Other Pydantic settings like
allow_population_by_field_name.
python
from pydantic import BaseModel class MyModel(BaseModel): id: int name: str class Config: orm_mode = True json_encoders = { # custom encoders here }
Example
This example shows a Pydantic model with Config enabling orm_mode. It allows FastAPI to return ORM objects directly as JSON responses.
python
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() # Simulate an ORM object class UserORM: def __init__(self, id: int, username: str): self.id = id self.username = username class User(BaseModel): id: int username: str class Config: orm_mode = True @app.get("/user", response_model=User) async def get_user(): user_orm = UserORM(id=1, username="alice") return user_orm
Output
{"id":1,"username":"alice"}
Common Pitfalls
One common mistake is forgetting to set orm_mode = True when returning ORM objects. Without it, FastAPI cannot convert ORM instances to JSON properly and raises errors.
Another pitfall is misconfiguring json_encoders which can cause serialization failures for custom types.
python
from pydantic import BaseModel # Wrong: missing orm_mode class UserWrong(BaseModel): id: int username: str # Right: orm_mode enabled class UserRight(BaseModel): id: int username: str class Config: orm_mode = True
Quick Reference
| Config Option | Purpose | Example Value |
|---|---|---|
| orm_mode | Allows model to read ORM objects | True |
| json_encoders | Custom JSON serialization for types | {datetime: lambda v: v.isoformat()} |
| allow_population_by_field_name | Allow using field names in input | True |
| anystr_strip_whitespace | Strip whitespace from strings | True |
Key Takeaways
Use a nested Config class inside your Pydantic model to customize behavior.
Set orm_mode = True to enable compatibility with ORM objects in FastAPI.
Use json_encoders in Config to customize JSON output for special types.
Forgetting orm_mode causes errors when returning ORM instances as responses.
Config options help tailor validation and serialization to your app needs.