Introduction
When working with FastAPI and SQLAlchemy, you may have seen this line in Pydantic schemas:
class Config:
orm_mode = TrueMany beginners copy this without understanding why it is needed.
In this article, we will explain what orm_mode does and why it is important.
The Problem
FastAPI uses Pydantic to validate and serialize data. However, SQLAlchemy returns database objects, not dictionaries.
For example:
user = db.query(User).first()This returns a SQLAlchemy model object, not a JSON-friendly format. Pydantic cannot directly convert this object into JSON.
The Solution
To fix this, we enable orm_mode.
class UserResponse(BaseModel):
id: int
name: str
class Config:
orm_mode = TrueHow It Works
When orm_mode = True is enabled:
- Pydantic reads data from object attributes
- It converts SQLAlchemy objects into JSON automatically
Without it, you may get errors like:
value is not a valid dictTo understand how it works in real CRUD API, I recommend you to read the following tutorial:
FastAPI CRUD Tutorial with SQLAlchemy and PostgreSQL
Conclusion
orm_mode = True allows FastAPI to work smoothly with SQLAlchemy models.
Without it, FastAPI cannot convert database objects into API responses.
So whenever you use SQLAlchemy models in responses, always enable orm_mode.