Bird
0
0

In FastAPI, how can you apply a global dependency that provides a database session to all routes but override it with a different session provider for a specific APIRouter?

hard🚀 Application Q8 of 15
FastAPI - Dependency Injection
In FastAPI, how can you apply a global dependency that provides a database session to all routes but override it with a different session provider for a specific APIRouter?
AAdd the global dependency in FastAPI(dependencies=...) and override it by specifying dependencies in the APIRouter constructor
BUse middleware for the global session and dependencies for the router session
CDefine the global dependency inside the router instead of the app
DYou cannot override global dependencies for specific routers
Step-by-Step Solution
Solution:
  1. Step 1: Understand global and router dependencies

    Global dependencies are set on the FastAPI app and apply to all routes unless overridden.
  2. Step 2: Override at router level

    APIRouter accepts a dependencies parameter that can override or add dependencies for its routes.
  3. Step 3: Eliminate other options

    Middleware is not used for dependencies, defining global dependency inside router limits scope, and overriding is allowed.
  4. Final Answer:

    Add the global dependency in FastAPI(dependencies=...) and override it by specifying dependencies in the APIRouter constructor -> Option A
  5. Quick Check:

    Router dependencies override global ones [OK]
Quick Trick: Router dependencies override app-level global dependencies [OK]
Common Mistakes:
MISTAKES
  • Using middleware instead of dependencies
  • Defining global dependency only inside router
  • Thinking global dependencies cannot be overridden

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes