0
0
FastAPIframework~20 mins

Database session management in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
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.