How does SQLAlchemy async work with FastAPI?
Why Interviewers Ask This
This question targets practical, hands-on experience with FastAPI / Flask. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
FastAPI's async support is best paired with SQLAlchemy 1.4+ async engine and asyncpg (PostgreSQL async driver). Setup: from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine; engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db"); async_session = sessionmaker(engine, class_=AsyncSession). Create a dependency: async def get_db(): async with async_session() as session: yield session. Use in routes: result = await db.execute(select(User).where(User.id == id)); user = result.scalar_one_or_none(). The async SQLAlchemy style uses explicit SQL expressions rather than the ORM query API. Key difference from sync SQLAlchemy: db.query(User) becomes await db.execute(select(User)). With async SQLAlchemy + asyncpg, FastAPI can handle thousands of concurrent DB queries per second without thread pool exhaustion.
Pro Tip
This topic has FastAPI / Flask-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.
Previous
How do you implement JWT authentication in FastAPI?
Next
What is Flask's application factory pattern?
More FastAPI / Flask Questions
View all →- Intermediate How do you implement JWT authentication in FastAPI?
- Intermediate What is Flask's application factory pattern?
- Intermediate How do you implement background tasks in FastAPI?
- Intermediate What is Pydantic v2 and what changed from v1?
- Intermediate How do you implement middleware in FastAPI?