Discover how to stop repeating yourself and make your FastAPI routes smarter with just a few lines!
Why Dependencies with parameters in FastAPI? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine building a web app where you need to check user permissions or fetch data based on user input for every request manually.
You write repetitive code in every route to handle these checks and data fetching.
Manually repeating the same logic in every route is tiring and error-prone.
If you forget to add the check somewhere, your app might expose sensitive data or behave inconsistently.
It also makes your code messy and hard to maintain.
FastAPI's dependencies with parameters let you write reusable functions that accept inputs and run automatically before your route logic.
This keeps your routes clean and ensures consistent behavior everywhere.
def get_user(request): user_id = request.query_params.get('user_id') # manually fetch user and check permissions @app.get('/items') def read_items(request): user = get_user(request) # route logic here
from fastapi import Query, Depends from fastapi import FastAPI app = FastAPI() def get_user(user_id: str = Query(...)): # fetch user and check permissions return user_id @app.get('/items') def read_items(user=Depends(get_user)): # route logic here return {"user": user}
You can build clean, secure, and reusable request handling that adapts based on input parameters automatically.
In an online store, you can create a dependency that checks if a user is an admin based on a token parameter, and reuse it in all admin routes without repeating code.
Manual checks in every route cause repetition and errors.
Dependencies with parameters let you reuse logic with inputs.
This makes your FastAPI code cleaner, safer, and easier to maintain.
Practice
Solution
Step 1: Understand dependency role
Dependencies in FastAPI are reusable pieces of code that can be shared across routes.Step 2: Recognize parameter use
Adding parameters to dependencies allows customizing their behavior for different routes or situations.Final Answer:
To customize shared code by passing arguments to dependencies -> Option DQuick Check:
Dependencies with parameters = customize shared code [OK]
- Thinking dependencies create global variables
- Confusing dependencies with route handlers
- Assuming dependencies generate HTML
Solution
Step 1: Recall Depends usage
Depends expects a callable or a call to a callable that returns a dependency.Step 2: Passing parameters
To pass parameters, you call the dependency function inside Depends, like Depends(get_user(user_id=5)).Final Answer:
Depends(get_user(user_id=5)) -> Option AQuick Check:
Call dependency inside Depends to pass parameters [OK]
- Passing parameters directly to Depends without calling
- Using brackets [] instead of parentheses ()
- Trying to call Depends as a function with parameters
from fastapi import FastAPI, Depends
app = FastAPI()
def get_multiplier(factor: int):
def multiplier(value: int):
return value * factor
return multiplier
@app.get("/multiply")
async def multiply(value: int, multiply_func = Depends(get_multiplier(3))):
return {"result": multiply_func(value)}Solution
Step 1: Understand get_multiplier
get_multiplier(3) returns a function that multiplies input by 3.Step 2: Analyze endpoint call
When calling /multiply with value=3, multiply_func(3) returns 3 * 3 = 9.Final Answer:
{"result": 9} when value=3 -> Option CQuick Check:
Dependency returns multiplier with factor 3, output 9 [OK]
- Assuming Depends cannot take parameters
- Confusing returned function with direct value
- Mixing up multiplication factor
def get_limit(limit: int = 10):
return limit
@app.get("/items")
async def read_items(limit = Depends(get_limit(limit=20))):
return {"limit": limit}Solution
Step 1: Check Depends usage
Depends expects a callable or a call to a callable without parameters directly inside Depends.Step 2: Correct way to pass parameters
To pass parameters, wrap get_limit in another function or use a lambda to supply parameters.Final Answer:
Cannot pass parameters directly inside Depends like get_limit(limit=20) -> Option BQuick Check:
Depends() must wrap callable, not call with parameters directly [OK]
- Calling dependency with parameters inside Depends directly
- Ignoring need for wrapper function
- Wrong import path for Depends
def common_dep(param: str):
def dependency():
return f"Value is {param}"
return dependency
@app.get("/route1")
async def route1(dep = Depends(common_dep("A"))):
return {"msg": dep}
@app.get("/route2")
async def route2(dep = Depends(common_dep("B"))):
return {"msg": dep}Solution
Step 1: Understand reusable dependency pattern
Define a function that returns a dependency function customized by parameters.Step 2: Apply pattern per route
Call this function with different parameters inside Depends for each route to customize behavior.Final Answer:
Define a function returning a dependency function with parameter, then call it inside Depends -> Option AQuick Check:
Wrap dependency with parameter function, call inside Depends [OK]
- Using global variables instead of parameters
- Passing parameters directly to Depends without wrapping
- Duplicating dependency functions unnecessarily
