Describe SQLAlchemy setup in FastAPI from database config to endpoint

Tests FastAPI dependency injection and SQLAlchemy session lifecycle. Good answers cover: engine with pooling, declarative models, a yield-based session dependency, and endpoint queries. Red flag: engine per request or global session shared everywhere.
What's really being asked
This question checks whether you can wire up a real relational database stack in FastAPI without relying on copy-paste boilerplate. The interviewer wants to see that you understand object-relational mapping, connection pooling, dependency injection, and request-scoped session lifecycle. At the senior level, they also care that you know why each piece exists rather than simply naming files.
The full answer
First, the engine. You create a single SQLAlchemy engine using create_engine with a PostgreSQL connection string and configure a connection pool. This engine is a global singleton because it manages TCP connections to the database. Second, the declarative base and models. You define a Base class and a User model with columns, types, and a table name so SQLAlchemy knows how to map Python objects to PostgreSQL rows. Third, the session factory and dependency. You use sessionmaker bound to the engine, then write an async or sync dependency that yields a Session, performs rollback on exception, and always closes the session in a finally block. Fourth, the endpoint. You declare the session as a FastAPI dependency using Depends, run a query such as db.query(User).all(), and return the results. The dependency injection system ensures every request gets its own session.
The mistakes people make
A major red flag is creating a brand new engine inside the endpoint function. Engines are expensive to initialize and manage connection pools, so they belong at module level. Another red flag is using a single global Session object shared by every request, which is not thread-safe or async-safe and will corrupt transactions. Candidates also stumble by forgetting to close sessions, which leaks connections and exhausts the pool. Finally, mixing sync SQLAlchemy with async path operations without using AsyncSession and an async engine shows a lack of attention to FastAPI's concurrency model.
What usually comes next
The interviewer may ask how you would handle database migrations, which opens the door to Alembic. They might ask how to test this endpoint, where the correct pattern is to override the session dependency with a test database. They could also ask about connection pool tuning for production, such as setting pool_size and max_overflow, or how to use lifespan events to create tables on startup instead of doing it manually.
A concrete example
Imagine a PostgreSQL URL of postgresql://user:pass@localhost/db. You define engine = create_engine(DATABASE_URL, pool_size=10) at the top of database.py. You define class User(Base) with id and email columns. You define SessionLocal = sessionmaker(bind=engine). Then you write a get_db dependency that instantiates db = SessionLocal(), yields it, and closes it in a finally block. In the FastAPI endpoint @app.get("/users") you write def read_users(db: Session = Depends(get_db)): return db.query(User).all(). This gives every caller a clean session while reusing the same connection pool.
Interview question
Which pattern correctly wires SQLAlchemy from configuration to endpoint in FastAPI without risking connection leaks?
- a.Create a new engine with create_engine inside each endpoint and instantiate a fresh Session per request.
- b.Build the session inside a startup event handler and attach it to application state for endpoints to share.
- c.Instantiate a single global Session at import time and use it directly in every endpoint query.
- d.Define a module-level engine and sessionmaker, then yield request-scoped sessions in a dependency with cleanup in a finally block.Correct
Why? this is the answer
Option D is correct because a single engine manages the connection pool globally, and yielding sessions with a finally block ensures each request gets its own safely closed session. Option A is tempting but wrong because creating an engine per request is expensive and defeats connection pooling, quickly exhausting database resources.
Just read this? Test yourself on what you have been reading.
Read the original → fastapi.tiangolo.com
- #fastapi
- #sqlalchemy
- #postgresql
- #dependency-injection
- #python
You just looked this up. Could you explain it out loud?
That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on fastapi — each one lists the topics its interview covers.
See open roles