Bird
Raised Fist0
FastAPIframework~20 mins

Database session management in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

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
Challenge - 5 Problems
🎖️
Database Session Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a FastAPI endpoint uses a database session dependency incorrectly?

Consider a FastAPI endpoint that uses a database session dependency but forgets to close the session after use. What is the likely outcome?

FastAPI
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session

app = FastAPI()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        pass  # missing db.close()

@app.get("/items/")
def read_items(db: Session = Depends(get_db)):
    return db.query(Item).all()
AThe database session will automatically close without any issues.
BThe endpoint will raise a SyntaxError due to missing db.close() call.
CDatabase connections will remain open, potentially causing connection pool exhaustion.
DThe endpoint will return an empty list regardless of database content.
Attempts:
2 left
💡 Hint

Think about what happens if you open a resource but never close it.

📝 Syntax
intermediate
2:00remaining
Which code snippet correctly manages a SQLAlchemy session in FastAPI?

Choose the code snippet that correctly creates and closes a SQLAlchemy session using FastAPI dependency injection.

A
def get_db():
    db = SessionLocal()
    yield db
    # no close call
B
def get_db():
    db = SessionLocal()
    yield db
    db.close()
C
def get_db():
    db = SessionLocal()
    try:
        yield db
    except:
        db.close()
D
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
Attempts:
2 left
💡 Hint

Consider how to guarantee cleanup even if an error occurs.

state_output
advanced
2:00remaining
What is the state of the database session after the endpoint finishes execution?

Given this FastAPI dependency for database session management, what is the state of the session after the endpoint returns?

FastAPI
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/users/")
def read_users(db: Session = Depends(get_db)):
    users = db.query(User).all()
    return users
AThe session is closed and all resources are released.
BThe session remains open and can be reused by other requests.
CThe session is rolled back but not closed.
DThe session is committed but not closed.
Attempts:
2 left
💡 Hint

Look at what happens in the finally block.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI app raise 'InvalidRequestError: Session is closed'?

Examine the code below. Why does the app raise 'InvalidRequestError: Session is closed' when trying to query the database?

FastAPI
def get_db():
    db = SessionLocal()
    try:
        db.close()
        yield db
    except Exception:
        db.rollback()

@app.get("/products/")
def read_products(db: Session = Depends(get_db)):
    products = db.query(Product).all()
    return products
Adb.rollback() is called without an active transaction, causing the error.
Bdb.close() is called before the endpoint finishes, closing the session too early.
CThe session is never closed, causing resource leaks.
DThe dependency function is missing a yield statement.
Attempts:
2 left
💡 Hint

Check the order of yield and db.close() calls.

🧠 Conceptual
expert
2:00remaining
Why use dependency injection for database sessions in FastAPI?

What is the main advantage of using dependency injection to manage database sessions in FastAPI applications?

AIt ensures each request gets a fresh session that is properly closed, preventing connection leaks.
BIt allows sessions to be shared globally across all requests for performance.
CIt automatically commits all transactions without explicit calls.
DIt removes the need to import SQLAlchemy in endpoint code.
Attempts:
2 left
💡 Hint

Think about resource management and request isolation.

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

  1. 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.
  2. Step 2: Recognize safe database session management

    This ensures that each request has its own session, preventing conflicts and resource leaks.
  3. Final Answer:

    To create and close a database session for each request safely -> Option A
  4. Quick Check:

    Database session management = create and close session [OK]
Hint: Remember: get_db opens and closes sessions per request [OK]
Common Mistakes:
  • Thinking get_db stores data permanently
  • Confusing get_db with HTTP request handling
  • Assuming get_db generates HTML
2. Which of the following is the correct way to declare a dependency for a database session in a FastAPI route using Depends?
easy
A. def read_items(db = Depends(Session)):
B. def read_items(db: get_db = Session()):
C. def read_items(db: Session = get_db()):
D. def read_items(db: Session = Depends(get_db)):

Solution

  1. Step 1: Understand FastAPI dependency injection syntax

    FastAPI uses Depends to inject dependencies like database sessions into route functions.
  2. 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.
  3. Final Answer:

    def read_items(db: Session = Depends(get_db)): -> Option D
  4. 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

  1. 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.
  2. Step 2: Understand the route's database query

    The route uses the session to query all Item records and returns them as a list.
  3. Final Answer:

    A list of all items from the database -> Option C
  4. 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

  1. 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.
  2. Step 2: Understand proper session cleanup

    Using try-finally ensures the session closes even if errors occur during request handling.
  3. Final Answer:

    The session is closed after yield, so it may not close if an exception occurs -> Option B
  4. 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

  1. Step 1: Understand transaction management needs

    We want to commit changes only if no errors occur, otherwise rollback to avoid partial changes.
  2. 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.
  3. Final Answer:

    def get_db(): db = Session() try: yield db db.commit() except: db.rollback() raise finally: db.close() -> Option A
  4. Quick Check:

    Commit on success, rollback on error, always close [OK]
Hint: Use try-except-finally to commit, rollback, and close sessions [OK]
Common Mistakes:
  • Committing after yield without error handling
  • Not rolling back on exceptions
  • Closing session without try-finally