Bird
Raised Fist0
FastAPIframework~10 mins

Shared dependencies across routers in FastAPI - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Shared dependencies across routers
Define Dependency Function
↓
Create Router A with Dependency
↓
Create Router B with Dependency
↓
Include Routers in Main App
↓
Request to Router A or B
↓
Dependency Injected Automatically
↓
Endpoint Executes Using Dependency
This flow shows how a single dependency function is defined once and shared across multiple routers, which are then included in the main FastAPI app. When a request hits any router, the shared dependency is automatically injected.
Execution Sample
FastAPI
from fastapi import FastAPI, APIRouter, Depends

def common_dep():
    return "shared data"

router_a = APIRouter(dependencies=[Depends(common_dep)])
router_b = APIRouter(dependencies=[Depends(common_dep)])

app = FastAPI()
app.include_router(router_a)
app.include_router(router_b)
Defines a shared dependency and attaches it to two routers so both use it automatically.
Execution Table
StepActionDependency CalledRouterResult
1Define common_dep functionNoN/AFunction ready
2Create router_a with Depends(common_dep)Norouter_aRouter ready with dependency
3Create router_b with Depends(common_dep)Norouter_bRouter ready with dependency
4Include router_a and router_b in FastAPI appNoappApp ready with routers
5Request to router_a endpointYesrouter_acommon_dep runs, returns 'shared data'
6Request to router_b endpointYesrouter_bcommon_dep runs, returns 'shared data'
7Request to app root (no dependency)NoappNo dependency called
ExitNo more requestsN/AN/AExecution ends
💡 No more requests to routers, execution stops
Variable Tracker
VariableStartAfter Step 5After Step 6Final
common_dep resultN/A"shared data""shared data""shared data"
router_a dependenciesDepends(common_dep)Depends(common_dep)Depends(common_dep)Depends(common_dep)
router_b dependenciesDepends(common_dep)Depends(common_dep)Depends(common_dep)Depends(common_dep)
Key Moments - 2 Insights
Why does common_dep run on requests to both router_a and router_b?
Because both routers include Depends(common_dep) in their dependencies list, so FastAPI injects it automatically on requests to any endpoint in those routers (see execution_table rows 5 and 6).
Does common_dep run when requesting the main app root without routers?
No, because the main app root does not have the dependency attached, so common_dep is not called (see execution_table row 7).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result of common_dep when a request hits router_b?
A"router_b"
B"shared data"
CNone
DError
💡 Hint
Check execution_table row 6 where router_b request calls common_dep returning 'shared data'
At which step does the dependency get injected for the first time?
AStep 5
BStep 2
CStep 4
DStep 1
💡 Hint
Look at execution_table row 5 where the first request triggers dependency injection
If we remove Depends(common_dep) from router_a, what changes in the execution table?
AStep 6 no longer calls common_dep
BStep 7 calls common_dep
CStep 5 no longer calls common_dep
DNo changes
💡 Hint
Refer to variable_tracker and execution_table rows 5 and 6 about which routers have the dependency
Concept Snapshot
Shared dependencies in FastAPI allow you to define a function once
and attach it to multiple routers using Depends().
When a request hits any router with that dependency,
FastAPI runs the dependency automatically.
This avoids repeating code and keeps routers clean.
Include routers in the main app to activate them.
Full Transcript
In FastAPI, you can create a dependency function that provides shared data or logic. This function is defined once, for example common_dep, which returns 'shared data'. You then create routers, like router_a and router_b, and attach this dependency to them using the dependencies parameter with Depends(common_dep). When you include these routers in the main FastAPI app, any request to endpoints inside these routers will automatically call common_dep before running the endpoint code. This means the shared dependency runs for both routers without repeating code. If you request the main app root without routers, the dependency does not run. This setup helps keep your code organized and efficient by sharing common logic across multiple routers.

Practice

(1/5)
1. What is the main benefit of using shared dependencies across routers in FastAPI?
easy
A. To disable dependency injection in routers
B. To make the API slower by adding extra layers
C. To force all routers to use the same path prefix
D. To avoid repeating the same dependency code in multiple routers

Solution

  1. Step 1: Understand what shared dependencies do

    Shared dependencies allow you to write a dependency once and apply it to many routers, avoiding repetition.
  2. Step 2: Identify the benefit in code maintenance

    This reduces duplicate code and makes the project easier to maintain and update.
  3. Final Answer:

    To avoid repeating the same dependency code in multiple routers -> Option D
  4. Quick Check:

    Shared dependencies = avoid repetition [OK]
Hint: Shared dependencies reduce repeated code across routers [OK]
Common Mistakes:
  • Thinking shared dependencies slow down the API
  • Confusing shared dependencies with path prefixes
  • Believing shared dependencies disable injection
2. Which is the correct way to apply a shared dependency to an APIRouter in FastAPI?
easy
A. router = APIRouter(shared_dependencies=[Depends(common_dep)])
B. router = APIRouter(dependencies=[Depends(common_dep)])
C. router = APIRouter(dependency=Depends(common_dep))
D. router = APIRouter(shared=Depends(common_dep))

Solution

  1. Step 1: Recall the APIRouter parameter for dependencies

    The correct parameter name is dependencies, which takes a list of Depends objects.
  2. Step 2: Match the syntax to the correct option

    router = APIRouter(dependencies=[Depends(common_dep)]) uses dependencies=[Depends(common_dep)], which is the correct syntax.
  3. Final Answer:

    router = APIRouter(dependencies=[Depends(common_dep)]) -> Option B
  4. Quick Check:

    dependencies param = correct syntax [OK]
Hint: Use 'dependencies' param with a list of Depends [OK]
Common Mistakes:
  • Using 'shared_dependencies' instead of 'dependencies'
  • Passing Depends directly without a list
  • Using wrong parameter names like 'dependency' or 'shared'
3. Given this code snippet, what will be printed when accessing /items/42?
from fastapi import FastAPI, APIRouter, Depends

app = FastAPI()

def common_dep():
    print("Common dependency called")

router = APIRouter(dependencies=[Depends(common_dep)])

@router.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

app.include_router(router)
medium
A. "Common dependency called" is printed once per request
B. An error occurs because common_dep is not awaited
C. Nothing is printed
D. "Common dependency called" is printed twice per request

Solution

  1. Step 1: Understand how dependencies run in FastAPI

    Dependencies listed in the router's dependencies run for every matching request automatically.
  2. Step 2: Analyze the print statement in common_dep

    Each time the endpoint is called, common_dep runs and prints "Common dependency called" once.
  3. Final Answer:

    "Common dependency called" is printed once per request -> Option A
  4. Quick Check:

    Router dependencies run once per request [OK]
Hint: Router dependencies run once per matching request [OK]
Common Mistakes:
  • Thinking dependencies run multiple times per request
  • Expecting no output from print statements
  • Confusing async with sync dependencies causing errors
4. Identify the error in this FastAPI router setup with shared dependencies:
from fastapi import APIRouter, Depends

def verify_token():
    pass

router = APIRouter(dependencies=Depends(verify_token))

@router.get("/secure")
async def secure_endpoint():
    return {"message": "Secure"}
medium
A. Depends should be inside a list in dependencies parameter
B. verify_token must return a value
C. APIRouter cannot have dependencies
D. The route path must start with a slash

Solution

  1. Step 1: Check the dependencies parameter type

    The dependencies parameter expects a list of Depends objects, not a single Depends instance.
  2. Step 2: Identify the correct syntax

    It should be dependencies=[Depends(verify_token)] to be valid.
  3. Final Answer:

    Depends should be inside a list in dependencies parameter -> Option A
  4. Quick Check:

    dependencies param requires a list [OK]
Hint: Always wrap Depends in a list for dependencies param [OK]
Common Mistakes:
  • Passing Depends directly without list
  • Assuming dependencies param accepts single Depends
  • Ignoring syntax errors from wrong dependencies format
5. You want to apply a shared dependency that extracts a user from a token to two routers, router_a and router_b. Which approach correctly shares the dependency without repeating code?
hard
A. Define the dependency in each route function separately in both routers
B. Include get_current_user as a parameter in FastAPI() app initialization
C. Add the dependency to each router using the dependencies parameter with Depends(get_current_user)
D. Use global variables to store the user and access it in routes

Solution

  1. Step 1: Understand how to share dependencies across routers

    Using the dependencies parameter in APIRouter allows applying a dependency to all routes in that router.
  2. Step 2: Apply the dependency to both routers

    Adding dependencies=[Depends(get_current_user)] to both router_a and router_b shares the logic without repeating it in each route.
  3. Final Answer:

    Add the dependency to each router using the dependencies parameter with Depends(get_current_user) -> Option C
  4. Quick Check:

    Shared dependencies via router dependencies param [OK]
Hint: Use dependencies param on routers to share common logic [OK]
Common Mistakes:
  • Repeating dependency code in every route
  • Trying to add dependencies in FastAPI app instead of routers
  • Using global variables instead of dependency injection
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard