Discover how to stop repeating yourself and make your FastAPI routes smarter with shared dependencies!
Why Shared dependencies across routers in FastAPI? - Purpose & Use Cases
Imagine building a web app with many routes, each needing the same setup like checking user login or connecting to a database.
You add this setup code inside every route manually.
Writing the same setup code in every route is tiring and easy to forget.
If you want to change the setup, you must update every route, which wastes time and causes bugs.
FastAPI lets you define shared dependencies once and apply them to many routes automatically.
This keeps your code clean, consistent, and easy to update.
def route1(): user = get_current_user() db = get_db() # route logic def route2(): user = get_current_user() db = get_db() # route logic
from fastapi import APIRouter, Depends shared_deps = [Depends(get_current_user), Depends(get_db)] router = APIRouter(dependencies=shared_deps) @router.get('/route1') async def route1(): # route logic @router.get('/route2') async def route2(): # route logic
You can manage common setup in one place and have all routes use it automatically, making your app easier to build and maintain.
A social media app where every page needs to check if the user is logged in and connect to the database before showing content.
Writing shared setup code once saves time and avoids mistakes.
FastAPI's shared dependencies keep routes clean and consistent.
Updating shared logic is easy and affects all routes automatically.
Practice
Solution
Step 1: Understand what shared dependencies do
Shared dependencies allow you to write a dependency once and apply it to many routers, avoiding repetition.Step 2: Identify the benefit in code maintenance
This reduces duplicate code and makes the project easier to maintain and update.Final Answer:
To avoid repeating the same dependency code in multiple routers -> Option DQuick Check:
Shared dependencies = avoid repetition [OK]
- Thinking shared dependencies slow down the API
- Confusing shared dependencies with path prefixes
- Believing shared dependencies disable injection
APIRouter in FastAPI?Solution
Step 1: Recall the APIRouter parameter for dependencies
The correct parameter name isdependencies, which takes a list of Depends objects.Step 2: Match the syntax to the correct option
router = APIRouter(dependencies=[Depends(common_dep)]) usesdependencies=[Depends(common_dep)], which is the correct syntax.Final Answer:
router = APIRouter(dependencies=[Depends(common_dep)]) -> Option BQuick Check:
dependencies param = correct syntax [OK]
- Using 'shared_dependencies' instead of 'dependencies'
- Passing Depends directly without a list
- Using wrong parameter names like 'dependency' or 'shared'
/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)Solution
Step 1: Understand how dependencies run in FastAPI
Dependencies listed in the router's dependencies run for every matching request automatically.Step 2: Analyze the print statement in common_dep
Each time the endpoint is called, common_dep runs and prints "Common dependency called" once.Final Answer:
"Common dependency called" is printed once per request -> Option AQuick Check:
Router dependencies run once per request [OK]
- Thinking dependencies run multiple times per request
- Expecting no output from print statements
- Confusing async with sync dependencies causing errors
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"}Solution
Step 1: Check the dependencies parameter type
The dependencies parameter expects a list of Depends objects, not a single Depends instance.Step 2: Identify the correct syntax
It should be dependencies=[Depends(verify_token)] to be valid.Final Answer:
Depends should be inside a list in dependencies parameter -> Option AQuick Check:
dependencies param requires a list [OK]
- Passing Depends directly without list
- Assuming dependencies param accepts single Depends
- Ignoring syntax errors from wrong dependencies format
router_a and router_b. Which approach correctly shares the dependency without repeating code?Solution
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.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.Final Answer:
Add the dependency to each router using the dependencies parameter with Depends(get_current_user) -> Option CQuick Check:
Shared dependencies via router dependencies param [OK]
- Repeating dependency code in every route
- Trying to add dependencies in FastAPI app instead of routers
- Using global variables instead of dependency injection
Ready to prove it?
Pass the test and this pattern moves unknown
