Path operation dependencies help you run shared code before your API handles a request. This keeps your code clean and avoids repeating yourself.
Path operation dependencies in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
from fastapi import FastAPI, Depends app = FastAPI() def common_dependency(): # code to run before path operation return 'some value' @app.get('/items/') async def read_items(dep_value: str = Depends(common_dependency)): return {'dep_value': dep_value}
Use Depends() to declare a dependency in a path operation function.
The dependency function runs first and its return value is passed to the path operation.
verify_token before the route and passes its result.from fastapi import FastAPI, Depends app = FastAPI() def verify_token(): return 'token verified' @app.get('/secure') async def secure_route(token_status: str = Depends(verify_token)): return {'status': token_status}
from fastapi import FastAPI, Depends app = FastAPI() def common_params(q: str | None = None): return q @app.get('/search') async def search(q: str | None = Depends(common_params)): return {'query': q}
This program defines a dependency get_token_header that runs before the /items/ route. The route receives the token value and returns it in the response.
from fastapi import FastAPI, Depends app = FastAPI() def get_token_header(): # Imagine checking a token here return 'token123' @app.get('/items/') async def read_items(token: str = Depends(get_token_header)): return {'token_received': token}
Dependencies can be reused in many routes to keep code DRY (Don't Repeat Yourself).
You can stack multiple dependencies by adding more parameters with Depends().
Dependencies can also raise errors to stop request processing early.
Path operation dependencies run shared code before handling requests.
Use Depends() to declare dependencies in your route functions.
This helps keep your API code clean and organized.
Practice
Depends() in FastAPI path operations?Solution
Step 1: Understand the role of
Depends()Depends()is used to declare dependencies that run shared code before the main path operation function executes.Step 2: Identify the purpose in FastAPI
This helps keep code clean by reusing common logic like authentication or database access.
Final Answer:
To run shared code before handling requests -> Option DQuick Check:
Depends() runs shared code before requests [OK]
- Thinking Depends() sets HTTP methods
- Confusing Depends() with response status codes
- Assuming Depends() manually creates DB connections
Solution
Step 1: Recall the syntax for dependencies
Dependencies are declared by assigning a parameter to
Depends()with the dependency function inside.Step 2: Check each option
def read_item(item_id: int, user=Depends(get_current_user)): correctly uses
user=Depends(get_current_user). Others have syntax errors or call the function directly.Final Answer:
def read_item(item_id: int, user=Depends(get_current_user)): -> Option CQuick Check:
Depends() with function inside parentheses [OK]
- Calling the dependency function directly
- Using Depends without parentheses
- Using square brackets instead of parentheses
/items/5?
from fastapi import FastAPI, Depends
app = FastAPI()
def get_token():
return "token123"
@app.get("/items/{item_id}")
def read_item(item_id: int, token: str = Depends(get_token)):
return {"item_id": item_id, "token": token}Solution
Step 1: Understand dependency execution
The
get_tokenfunction returns "token123" and is injected intotokenparameter viaDepends().Step 2: Check the returned dictionary
The path operation returns a dictionary with
item_idandtokenkeys, so the output includes the token string.Final Answer:
{"item_id": 5, "token": "token123"} -> Option AQuick Check:
Dependency injects token value correctly [OK]
- Expecting token to be null without dependency
- Thinking dependency causes runtime error
- Confusing syntax with runtime errors
from fastapi import FastAPI, Depends
app = FastAPI()
def get_user():
return "user1"
@app.get("/profile")
def profile(user: str = Depends(get_user)):
return {"user": user}
@app.get("/dashboard")
def dashboard(user = Depends(get_user)):
return {"dashboard_user": user}Solution
Step 1: Compare both path operation functions
The
profilefunction declaresuser: str = Depends(get_user)with a type annotation.Step 2: Identify the issue in
dashboardThe
dashboardfunction usesuser = Depends(get_user)but lacks a type annotation, which FastAPI requires for dependencies.Final Answer:
Missing type annotation for 'user' in dashboard function -> Option AQuick Check:
Dependency parameters need type annotations [OK]
- Omitting type annotations on dependency parameters
- Forgetting parentheses on Depends()
- Assuming missing decorator causes error
Solution
Step 1: Understand dependency chaining
You can call one dependency inside another to reuse logic and combine checks.
Step 2: Apply chaining for user extraction and active check
By calling the user extraction inside the active check dependency, you only need to use Depends() on the active check in routes.
Final Answer:
Call the user extraction function inside the active check function and use Depends() only on the active check -> Option BQuick Check:
Chain dependencies by calling one inside another [OK]
- Using multiple Depends() separately causing repeated calls
- Not chaining dependencies and duplicating code
- Checking user active status outside dependencies
