Bird
Raised Fist0
FastAPIframework~20 mins

Shared dependencies across routers in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
FastAPI Dependency Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when accessing the endpoint with shared dependency?

Consider a FastAPI app with two routers sharing a dependency that returns a user ID. What will the response be when calling /items/?

FastAPI
from fastapi import FastAPI, Depends, APIRouter

app = FastAPI()

async def get_user_id():
    return "user123"

router1 = APIRouter(dependencies=[Depends(get_user_id)])

@router1.get("/items/")
async def read_items():
    return {"message": "Items accessed"}

router2 = APIRouter(dependencies=[Depends(get_user_id)])

@router2.get("/users/")
async def read_users():
    return {"message": "Users accessed"}

app.include_router(router1)
app.include_router(router2)
A{"detail": "Not Found"}
B{"message": "Users accessed"}
CRuntimeError due to dependency conflict
D{"message": "Items accessed"}
Attempts:
2 left
💡 Hint

Think about which router handles the /items/ path and what the shared dependency returns.

📝 Syntax
intermediate
2:00remaining
Which option correctly applies a shared dependency to multiple routers?

Given two routers, which code snippet correctly applies the same dependency to both routers?

FastAPI
from fastapi import APIRouter, Depends

async def common_dep():
    return "common"

router1 = APIRouter()
router2 = APIRouter()

# Which option correctly adds common_dep as a shared dependency?
A
router1 = APIRouter(dependencies=[Depends(common_dep)])
router2 = APIRouter(dependencies=[Depends(common_dep)])
B
router1.dependencies = [Depends(common_dep)]
router2.dependencies = [Depends(common_dep)]
C
router1 = APIRouter()
router2 = APIRouter()
router1.include_router(router2, dependencies=[Depends(common_dep)])
D
router1 = APIRouter(dependencies=Depends(common_dep))
router2 = APIRouter(dependencies=Depends(common_dep))
Attempts:
2 left
💡 Hint

Check how dependencies are passed as a list to the APIRouter constructor.

🔧 Debug
advanced
2:00remaining
Why does this shared dependency raise a runtime error?

Examine the code below. When running the app, a runtime error occurs related to the shared dependency. What causes this error?

FastAPI
from fastapi import FastAPI, Depends, APIRouter

app = FastAPI()

async def get_db():
    raise RuntimeError("DB connection failed")

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

@router.get("/data")
async def read_data():
    return {"data": "sample"}

app.include_router(router)
AThe dependency is not awaited properly, causing a coroutine warning.
BThe router is missing a prefix, causing routing errors.
CThe dependency get_db raises an exception, causing the endpoint to fail.
DFastAPI does not support async dependencies in routers.
Attempts:
2 left
💡 Hint

Look at what the dependency function does when called.

❓ state_output
advanced
2:00remaining
What is the value of the shared dependency parameter inside the endpoint?

Given this FastAPI router with a shared dependency that returns a string, what is the value of user inside the endpoint?

FastAPI
from fastapi import APIRouter, Depends

async def get_current_user():
    return "alice"

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

@router.get("/profile")
async def profile(user: str = Depends(get_current_user)):
    return {"user": user}
ANone
B"alice"
CRaises a TypeError due to duplicate dependency
D"user"
Attempts:
2 left
💡 Hint

Consider how FastAPI resolves dependencies when declared both in router and endpoint.

🧠 Conceptual
expert
2:00remaining
Why use shared dependencies at router level instead of endpoint level?

Which is the main advantage of applying dependencies at the router level instead of individually on each endpoint?

AIt ensures the dependency is executed once per request for all endpoints in the router, reducing code repetition.
BIt disables dependency injection for endpoints not needing it.
CIt automatically caches the dependency result across all requests.
DIt allows dependencies to modify the router's URL prefix dynamically.
Attempts:
2 left
💡 Hint

Think about code reuse and how dependencies apply to multiple endpoints.

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