Bird
0
0

What is wrong with this FastAPI route using a database session?

medium📝 Debug Q7 of 15
FastAPI - Database Integration
What is wrong with this FastAPI route using a database session? ```python @app.get("/users/{user_id}") def get_user(user_id: int, db: Session = Depends(get_db)): user = db.query(User).filter(User.id == user_id).first() db.close() return user ``` Options:
ADepends(get_db) is used incorrectly
BCalling db.close() inside the route can close session prematurely
CThe filter condition is invalid
DRoute must be async to use database session
Step-by-Step Solution
Solution:
  1. Step 1: Check session closing in route

    Calling db.close() manually in route can close session before response is fully processed.
  2. Step 2: Understand dependency management

    Session should be closed by dependency, not manually in route, to avoid premature closure.
  3. Final Answer:

    Calling db.close() inside the route can close session prematurely -> Option B
  4. Quick Check:

    Close session in dependency, not route [OK]
Quick Trick: Let dependency handle session close, not route code [OK]
Common Mistakes:
MISTAKES
  • Closing session manually in route
  • Misusing Depends syntax
  • Thinking route must be async for DB

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes