Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Recall & Review
beginner
What is the purpose of database session management in FastAPI?
It manages the connection to the database for each request, ensuring data consistency and proper resource use by opening and closing sessions as needed.
Click to reveal answer
intermediate
How do you typically create a database session in FastAPI using SQLAlchemy?
You create a session factory with sessionmaker, then use a dependency function that yields a session and closes it after the request.
Click to reveal answer
beginner
Why is it important to close the database session after each request?
Closing the session frees up database connections and avoids memory leaks, keeping the app efficient and stable.
Click to reveal answer
intermediate
What does the 'yield' keyword do in the FastAPI dependency that manages the database session?
It provides the session to the path operation and then resumes to close the session after the request finishes.
Click to reveal answer
advanced
How can you handle exceptions during database operations in a FastAPI session?
Use try-except blocks inside the session dependency or route, and rollback the session if an error occurs before closing it.
Click to reveal answer
What is the main role of the sessionmaker in FastAPI database management?
ATo handle HTTP requests
BTo close database connections automatically
CTo define database models
DTo create new database sessions
✗ Incorrect
Sessionmaker creates new database session objects used to interact with the database.
In FastAPI, how do you ensure a database session is closed after a request?
ABy manually calling close() in every route
BBy using a dependency with yield and closing the session after yield
CBy setting a global session variable
DBy restarting the server
✗ Incorrect
Using a dependency with yield allows automatic closing of the session after the request finishes.
What happens if you don't close database sessions properly in FastAPI?
ADatabase connections may leak and cause errors
BThe app runs faster
CNothing, sessions close automatically
DThe database schema changes
✗ Incorrect
Not closing sessions can cause connection leaks and degrade app performance.
Which Python keyword is used in FastAPI dependencies to manage setup and cleanup of database sessions?
Ayield
Basync
Creturn
Dawait
✗ Incorrect
The yield keyword allows the function to provide a session and then continue to cleanup after.
How do you handle errors during database operations in a FastAPI session?
AIgnore errors and continue
BClose the session without rollback
CUse try-except and rollback the session on error
DRestart the database server
✗ Incorrect
Using try-except and rolling back ensures the database stays consistent after errors.
Explain how to create and manage a database session in FastAPI using SQLAlchemy.
Think about how FastAPI dependencies help manage resources per request.
You got /4 concepts.
Describe why proper database session management is important in web applications.
Consider what happens if sessions stay open or errors are not handled.
You got /4 concepts.
Practice
(1/5)
1. What is the main purpose of using a get_db function in FastAPI when working with databases?
easy
A. To create and close a database session for each request safely
B. To store user data permanently in memory
C. To handle HTTP requests directly without a database
D. To generate HTML templates for responses
Solution
Step 1: Understand the role of get_db
The get_db function is designed to open a database session when a request starts and close it when the request ends.
FastAPI uses Depends to inject dependencies like database sessions into route functions.
Step 2: Correct syntax for session injection
The correct syntax is to type hint the parameter as Session and assign it Depends(get_db) to call the dependency function.
Final Answer:
def read_items(db: Session = Depends(get_db)): -> Option D
Quick Check:
Dependency injection = parameter: Type = Depends(function) [OK]
Hint: Use parameter: Type = Depends(function) for dependencies [OK]
Common Mistakes:
Calling get_db() directly in parameter default
Using Depends with a class instead of a function
Swapping parameter and default values
3. Given this FastAPI route code snippet, what will be the output if the database session is correctly managed?
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
app = FastAPI()
def get_db():
db = Session()
try:
yield db
finally:
db.close()
@app.get('/items')
def read_items(db: Session = Depends(get_db)):
items = db.query(Item).all()
return items
medium
A. An error because the session is not closed
B. An empty list because the query is missing
C. A list of all items from the database
D. A syntax error due to wrong yield usage
Solution
Step 1: Analyze the get_db function behavior
The get_db function creates a session, yields it for use, then closes it safely after the request.
Step 2: Understand the route's database query
The route uses the session to query all Item records and returns them as a list.
Final Answer:
A list of all items from the database -> Option C
Quick Check:
Yielded session + query = list of items [OK]
Hint: Yielded session allows safe query and close after use [OK]
Common Mistakes:
Assuming session is not closed causing error
Thinking yield causes syntax error
Believing query returns empty without data
4. Identify the error in this FastAPI database session management code:
def get_db():
db = Session()
yield db
db.close()
@app.post('/add')
def add_item(item: Item, db: Session = Depends(get_db)):
db.add(item)
db.commit()
medium
A. The item parameter should be inside get_db
B. The session is closed after yield, so it may not close if an exception occurs
C. The Depends is used incorrectly in the route
D. The db.commit() is missing
Solution
Step 1: Review session closing in get_db
The db.close() is called after yield without a try-finally block, so if an exception happens, the session may never close.
Step 2: Understand proper session cleanup
Using try-finally ensures the session closes even if errors occur during request handling.
Final Answer:
The session is closed after yield, so it may not close if an exception occurs -> Option B
Quick Check:
Session close needs try-finally for safety [OK]
Hint: Always use try-finally to close sessions safely [OK]
Common Mistakes:
Ignoring try-finally for session cleanup
Forgetting to commit changes
Misplacing Depends usage
5. You want to ensure that your FastAPI app's database sessions are properly managed and that any changes are committed only if no exceptions occur. Which of the following get_db implementations best achieves this?
hard
A. def get_db():
db = Session()
try:
yield db
db.commit()
except:
db.rollback()
raise
finally:
db.close()
B. def get_db():
db = Session()
yield db
db.commit()
db.close()
C. def get_db():
db = Session()
try:
yield db
finally:
db.close()
D. def get_db():
db = Session()
yield db
db.rollback()
db.close()
Solution
Step 1: Understand transaction management needs
We want to commit changes only if no errors occur, otherwise rollback to avoid partial changes.
Step 2: Analyze each get_db implementation
def get_db():
db = Session()
try:
yield db
db.commit()
except:
db.rollback()
raise
finally:
db.close() uses try-except-finally to commit on success, rollback on error, and always close the session, which is the safest approach.
Final Answer:
def get_db():
db = Session()
try:
yield db
db.commit()
except:
db.rollback()
raise
finally:
db.close() -> Option A
Quick Check:
Commit on success, rollback on error, always close [OK]
Hint: Use try-except-finally to commit, rollback, and close sessions [OK]