Bird
0
0

Given this FastAPI route code snippet, what will be the output if the database session is correctly managed?

medium📝 component behavior Q13 of 15
FastAPI - Database Integration
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
AAn error because the session is not closed
BAn empty list because the query is missing
CA list of all items from the database
DA syntax error due to wrong yield usage
Step-by-Step Solution
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]
Quick Trick: Yielded session allows safe query and close after use [OK]
Common Mistakes:
MISTAKES
  • Assuming session is not closed causing error
  • Thinking yield causes syntax error
  • Believing query returns empty without data

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes