0
0
FastAPIframework~20 mins

SQLAlchemy setup with FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
SQLAlchemy FastAPI Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this FastAPI endpoint using SQLAlchemy session?

Given this FastAPI endpoint code snippet, what will be the JSON response when a GET request is made to /users/1 assuming the user with ID 1 exists in the database?

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

app = FastAPI()

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

@app.get('/users/{user_id}')
async def read_user(user_id: int, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail='User not found')
    return {'id': user.id, 'name': user.name}
A{"id": 1, "name": "Alice"}
B{"detail": "User not found"}
C500 Internal Server Error
D{"id": 1, "username": "Alice"}
Attempts:
2 left
💡 Hint

Check what the endpoint returns when the user is found and how the dictionary keys are named.

📝 Syntax
intermediate
1:30remaining
Which option correctly creates a SQLAlchemy session dependency for FastAPI?

Choose the correct code snippet that defines a get_db dependency yielding a SQLAlchemy session and properly closing it after use.

A
def get_db():
    db = SessionLocal()
    return db
B
def get_db():
    db = SessionLocal()
    yield db
    db.close()
C
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
D
def get_db():
    with SessionLocal() as db:
        yield db
Attempts:
2 left
💡 Hint

Remember that yield inside try and finally ensures the session closes after use.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI app raise an error when accessing the database?

Consider this code snippet. What is the cause of the error when the endpoint tries to query the database?

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

app = FastAPI()

@app.get('/items')
async def read_items(db: Session = Depends()):
    items = db.query(Item).all()
    return items
AThe FastAPI app is missing middleware to handle database connections.
BThe Item model is not imported, causing a NameError.
CThe endpoint function is async but uses a synchronous DB session causing a runtime error.
DThe dependency for the database session is missing; Depends() needs a callable like get_db.
Attempts:
2 left
💡 Hint

Check the Depends() usage and what it expects as an argument.

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

Given this get_db dependency and endpoint, what happens to the database session after the endpoint returns the response?

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

@app.get('/data')
async def get_data(db: Session = Depends(get_db)):
    return db.query(Data).all()
AThe session is closed properly after the response is sent.
BThe session remains open and causes a connection leak.
CThe session is closed before the query runs, causing an error.
DThe session is committed automatically after the query.
Attempts:
2 left
💡 Hint

Think about how yield and finally work in the dependency.

🧠 Conceptual
expert
2:30remaining
Which statement best explains the role of SQLAlchemy sessions in FastAPI dependency injection?

Choose the most accurate explanation of why SQLAlchemy sessions are provided as dependencies in FastAPI endpoints.

ASessions are provided as dependencies to allow sharing the same session across all requests for performance.
BSessions are provided as dependencies to ensure each request gets a fresh session that is properly closed after use, preventing connection leaks.
CSessions are provided as dependencies to automatically commit all changes without explicit calls in the endpoint.
DSessions are provided as dependencies to cache query results globally across the app.
Attempts:
2 left
💡 Hint

Consider how database connections should be managed per request in web apps.