The Depends function helps you share and reuse code in FastAPI by letting you declare dependencies easily.
Depends function basics in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
FastAPI
from fastapi import FastAPI, Depends app = FastAPI() def common_logic(): # some reusable code return 'result' @app.get("/items/") async def read_items(data=Depends(common_logic)): return {"data": data}
Depends wraps a function that FastAPI will call automatically.
The result of the dependency function is passed as an argument to your route function.
Examples
FastAPI
from fastapi import FastAPI, Depends app = FastAPI() def get_token(): return "token123" @app.get("/secure-data") async def secure_data(token: str = Depends(get_token)): return {"token": token}
FastAPI
from fastapi import FastAPI, Depends app = FastAPI() def common_parameters(q: str = None): return {"q": q} @app.get("/search") async def search(params: dict = Depends(common_parameters)): return params
Sample Program
This program defines a dependency function get_message that returns a greeting string. The route /greet uses Depends to call this function automatically and returns its result in JSON.
FastAPI
from fastapi import FastAPI, Depends app = FastAPI() def get_message(): return "Hello from dependency!" @app.get("/greet") async def greet(message: str = Depends(get_message)): return {"message": message}
Important Notes
Dependencies can be functions or classes.
FastAPI handles calling dependencies and passing their results automatically.
Use dependencies to keep your code clean and reusable.
Summary
Depends helps reuse code by injecting dependencies into routes.
It makes your code cleaner and easier to maintain.
FastAPI calls dependency functions automatically and passes their results.
Practice
1. What is the main purpose of the
Depends function in FastAPI?easy
Solution
Step 1: Understand what Depends does
Dependsis used to declare dependencies that FastAPI will automatically provide to your route functions.Step 2: Identify the main use case
It helps inject reusable code like authentication, database sessions, or other shared logic into routes.Final Answer:
To inject dependencies automatically into path operation functions -> Option CQuick Check:
Depends injects dependencies = C [OK]
Hint: Depends injects reusable code into routes automatically [OK]
Common Mistakes:
- Confusing Depends with database or template functions
- Thinking Depends handles HTTP status codes
- Assuming Depends creates models
2. Which of the following is the correct way to declare a dependency in a FastAPI route using
Depends?easy
Solution
Step 1: Recall Depends syntax
The correct syntax is to assign the parameter a default value of Depends with the dependency function inside.Step 2: Match the correct option
def read_items(db=Depends(get_db)): pass usesdb=Depends(get_db), which is the proper way to declare a dependency.Final Answer:
def read_items(db=Depends(get_db)): pass -> Option AQuick Check:
Depends usage = parameter=Depends(function) [OK]
Hint: Use parameter=Depends(function) to declare dependencies [OK]
Common Mistakes:
- Using type annotation instead of default value for Depends
- Passing Depends without parentheses
- Assigning Depends without a function
3. Given the code below, what will be the output when accessing the
/items/ endpoint?from fastapi import FastAPI, Depends
app = FastAPI()
def get_number():
return 42
@app.get('/items/')
def read_items(number: int = Depends(get_number)):
return {"number": number}medium
Solution
Step 1: Understand dependency injection
Theget_numberfunction returns 42, and FastAPI injects this value into thenumberparameter.Step 2: Check the returned response
The route returns a dictionary with key "number" and value 42, so the output is {"number": 42}.Final Answer:
{"number": 42} -> Option BQuick Check:
Depends injects 42 = {"number": 42} [OK]
Hint: Depends calls function and injects return value [OK]
Common Mistakes:
- Expecting the function name instead of its return value
- Thinking parameter is missing if not passed explicitly
- Assuming null is returned if no argument given
4. What is wrong with the following FastAPI code using
Depends? How to fix it?from fastapi import FastAPI, Depends
app = FastAPI()
def get_user():
return "Alice"
@app.get('/user/')
def read_user(user: str = Depends):
return {"user": user}medium
Solution
Step 1: Identify the Depends usage error
The parameter usesDependswithout specifying the dependency function, which is incorrect.Step 2: Correct the Depends syntax
It should beDepends(get_user)to tell FastAPI which function to call for the dependency.Final Answer:
Depends is missing the dependency function; fix by using Depends(get_user) -> Option AQuick Check:
Depends needs function argument = Depends(get_user) [OK]
Hint: Always pass the dependency function inside Depends() [OK]
Common Mistakes:
- Using Depends without parentheses or function
- Changing route path unnecessarily
- Changing return type without reason
5. How can you use
Depends to share a database session across multiple routes without repeating code? Choose the best approach.hard
Solution
Step 1: Understand code reuse with Depends
Depends allows you to write a function that creates or yields a database session once and injects it wherever needed.Step 2: Identify the best practice
Creating a session function and using Depends on it in routes avoids repetition and manages session lifecycle cleanly.Final Answer:
Create a function that returns the session and use Depends on it in each route -> Option DQuick Check:
Use Depends with session function for reuse = D [OK]
Hint: Use Depends with a session function to share DB session [OK]
Common Mistakes:
- Using global variables for sessions (not safe)
- Creating sessions manually in every route (repetitive)
- Using Depends without specifying a function
