Async Database Operations with SQLModel in FastAPI 2026
Modern web applications demand high performance and scalability. In 2026, using asynchronous database operations with SQLModel has become the standard approach for building fast and responsive FastAPI applications.
TL;DR — Key Takeaways 2026
- Use SQLModel with async database drivers (asyncpg for PostgreSQL)
- Always use
async deffor database operations - Leverage dependency injection for database sessions
- Use
select()with async sessions for queries - Proper session management prevents connection leaks
1. Modern Database Setup
# app/core/database.py
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlmodel import SQLModel
DATABASE_URL = "postgresql+asyncpg://user:pass@localhost/dbname"
engine = create_async_engine(DATABASE_URL, echo=True)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def get_session():
async with AsyncSessionLocal() as session:
yield session
2. Models with SQLModel
from sqlmodel import SQLModel, Field
from typing import Optional
class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
username: str = Field(index=True, unique=True)
email: str = Field(index=True, unique=True)
hashed_password: str
is_active: bool = True
3. Async CRUD Operations
from fastapi import Depends
from sqlmodel import select
from app.core.database import get_session
@app.post("/users/")
async def create_user(user: UserCreate, session: AsyncSession = Depends(get_session)):
db_user = User.model_validate(user)
db_user.hashed_password = hash_password(user.password)
session.add(db_user)
await session.commit()
await session.refresh(db_user)
return db_user
@app.get("/users/{user_id}")
async def read_user(user_id: int, session: AsyncSession = Depends(get_session)):
statement = select(User).where(User.id == user_id)
result = await session.exec(statement)
user = result.first()
return user
Best Practices 2026
- Always use
async deffor endpoints that interact with the database - Use dependency injection for database sessions
- Prefer
select()statements over raw SQL when possible - Always commit and refresh after mutations
- Use connection pooling and proper async drivers (asyncpg for PostgreSQL)
Conclusion
Async database operations with SQLModel have become the standard for FastAPI applications in 2026. This combination provides excellent performance, type safety, and developer experience while maintaining clean and maintainable code.
Next steps:
- Refactor your existing database operations to use async SQLModel patterns
- Related articles: FastAPI Project Structure Best Practices 2026 • Modern Web Development Best Practices 2026