Bird
0
0

Why does FastAPI recommend using shared dependencies with Depends() instead of calling functions directly inside route handlers?

hard🧠 Conceptual Q10 of 15
FastAPI - Dependency Injection
Why does FastAPI recommend using shared dependencies with Depends() instead of calling functions directly inside route handlers?
ABecause <code>Depends()</code> manages execution order, caching, and cleanup automatically.
BBecause calling functions directly causes syntax errors in FastAPI.
CBecause <code>Depends()</code> disables all logging for dependencies.
DBecause calling functions directly is slower than using <code>Depends()</code>.
Step-by-Step Solution
Solution:
  1. Step 1: Understand what Depends manages

    Depends() allows FastAPI to control when and how dependencies run, including caching results per request and running cleanup code.

  2. Step 2: Why not call functions directly

    Calling functions directly bypasses FastAPI's dependency system, losing benefits like automatic cleanup and proper execution order.

  3. Final Answer:

    Depends() manages execution order, caching, and cleanup automatically. -> Option A
  4. Quick Check:

    Depends controls lifecycle and caching [OK]
Quick Trick: Depends controls lifecycle, caching, and cleanup [OK]
Common Mistakes:
MISTAKES
  • Thinking direct calls cause syntax errors
  • Believing Depends disables logging
  • Assuming direct calls are always slower

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes