Bird
0
0

Which of the following code snippets correctly uses a shared dependency in FastAPI?

easy📝 Syntax Q3 of 15
FastAPI - Dependency Injection
Which of the following code snippets correctly uses a shared dependency in FastAPI?
Aasync def get_db(): pass @app.get('/items') async def read_items(db=get_db()): pass
Basync def get_db(): pass @app.get('/items') async def read_items(db=Depends(get_db)): pass
Casync def get_db(): pass @app.get('/items') async def read_items(db=Depends(get_db())): pass
Dasync def get_db(): pass @app.get('/items') async def read_items(db=Depends): pass
Step-by-Step Solution
Solution:
  1. Step 1: Check how dependency is passed

    Dependency functions should be passed as callable to Depends() without calling them.

  2. Step 2: Validate each option

    async def get_db(): pass @app.get('/items') async def read_items(db=Depends(get_db)): pass correctly passes get_db as callable. Options B and C call the function directly, and D passes Depends without callable.

  3. Final Answer:

    async def get_db(): pass @app.get('/items') async def read_items(db=Depends(get_db)): pass -> Option B
  4. Quick Check:

    Depends needs callable, not called function [OK]
Quick Trick: Use Depends with function name only, no parentheses [OK]
Common Mistakes:
MISTAKES
  • Calling dependency function inside Depends
  • Passing Depends without argument
  • Calling dependency function directly in parameter

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes