Bird
0
0

Which of the following is the correct way to declare a dependency for a database session in a FastAPI route using Depends?

easy📝 Syntax Q12 of 15
FastAPI - Database Integration
Which of the following is the correct way to declare a dependency for a database session in a FastAPI route using Depends?
Adef read_items(db = Depends(Session)):
Bdef read_items(db: get_db = Session()):
Cdef read_items(db: Session = get_db()):
Ddef read_items(db: Session = Depends(get_db)):
Step-by-Step Solution
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]
Quick Trick: Use parameter: Type = Depends(function) for dependencies [OK]
Common Mistakes:
MISTAKES
  • Calling get_db() directly in parameter default
  • Using Depends with a class instead of a function
  • Swapping parameter and default values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes