Sub-dependencies help you organize and reuse small parts of your code that other parts depend on. They make your code cleaner and easier to manage.
Sub-dependencies in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
from fastapi import FastAPI, Depends app = FastAPI() def sub_dependency(): return "sub value" def main_dependency(sub_val: str = Depends(sub_dependency)): return f"main uses {sub_val}" @app.get("/items/") async def read_items(dep: str = Depends(main_dependency)): return {"dep": dep}
Use Depends() inside another dependency function to create sub-dependencies.
FastAPI will resolve sub-dependencies automatically when you call the main dependency.
get_token used inside verify_token to check a token.from fastapi import Depends, HTTPException def get_token(): return "token123" def verify_token(token: str = Depends(get_token)): if token != "token123": raise HTTPException(status_code=401) return True
get_db is a sub-dependency that provides a database connection to get_user.from fastapi import Depends def get_db(): db = "database connection" try: yield db finally: print("close db") def get_user(db = Depends(get_db)): return f"user from {db}"
This program uses sub-dependencies to check a token before giving access to protected data. get_token provides the token, verify_token checks it, and get_data returns data if the token is valid.
from fastapi import FastAPI, Depends, HTTPException app = FastAPI() def get_token(): return "secret-token" def verify_token(token: str = Depends(get_token)): if token != "secret-token": raise HTTPException(status_code=401, detail="Invalid token") return token def get_data(token: str = Depends(verify_token)): return {"data": "Here is your protected data."} @app.get("/protected") async def protected_route(data = Depends(get_data)): return data
Sub-dependencies help keep your code modular and easier to test.
FastAPI resolves sub-dependencies automatically in the right order.
Use sub-dependencies to share common logic like authentication or database access.
Sub-dependencies let you reuse small parts of code inside other dependencies.
They make your code cleaner and easier to maintain.
FastAPI handles sub-dependencies automatically for you.
Practice
Solution
Step 1: Understand what sub-dependencies do
Sub-dependencies allow you to reuse small parts of code inside other dependencies, making your code cleaner.Step 2: Compare options with this purpose
Only To reuse small parts of code inside other dependencies correctly describes this purpose; others describe unrelated tasks.Final Answer:
To reuse small parts of code inside other dependencies -> Option CQuick Check:
Sub-dependencies = Reuse code [OK]
- Thinking sub-dependencies handle HTTP requests directly
- Confusing sub-dependencies with middleware
- Assuming sub-dependencies only manage database connections
Solution
Step 1: Recall FastAPI dependency syntax
Dependencies must be passed as functions inside Depends(), not called directly.Step 2: Analyze each option
def sub_dep(): return 'data' def main_dep(sub: str = Depends(sub_dep)): return sub correctly uses Depends(sub_dep) without calling it. Options B and C call the function, which is incorrect. def sub_dep(): return 'data' def main_dep(sub: str): return sub lacks Depends entirely.Final Answer:
def sub_dep(): return 'data'\n\ndef main_dep(sub: str = Depends(sub_dep)): return sub -> Option AQuick Check:
Use Depends(function) without parentheses [OK]
- Calling the dependency function inside Depends()
- Not using Depends at all
- Passing the function call result instead of the function
/items/42?
from fastapi import FastAPI, Depends
app = FastAPI()
def sub_dep():
return "sub-data"
def main_dep(data: str = Depends(sub_dep)):
return f"main uses {data}"
@app.get("/items/{item_id}")
async def read_item(item_id: int, info: str = Depends(main_dep)):
return {"item_id": item_id, "info": info}Solution
Step 1: Understand dependency chaining
Theread_itemendpoint depends onmain_dep, which depends onsub_dep. The value fromsub_depis passed tomain_dep.Step 2: Trace returned values
sub_dep()returns "sub-data".main_depreturns "main uses sub-data". Soinfoinread_itemis "main uses sub-data".Final Answer:
{"item_id": 42, "info": "main uses sub-data"} -> Option BQuick Check:
Sub-dependencies chain output correctly [OK]
- Ignoring sub-dependency output in main dependency
- Assuming direct sub_dep output is returned
- Expecting runtime errors without cause
from fastapi import FastAPI, Depends
app = FastAPI()
def sub_dep():
return "data"
def main_dep(data: str = Depends(sub_dep)):
return data
@app.get("/test")
async def test_endpoint(info: str = Depends(main_dep())):
return {"info": info}Solution
Step 1: Identify how Depends should be used
Depends expects a function reference, not a function call. Calling main_dep() executes it immediately, which is wrong.Step 2: Check the code for this mistake
The code uses Depends(main_dep()), which calls the function instead of passing it. It should be Depends(main_dep).Final Answer:
Calling main_dep() inside Depends instead of passing the function -> Option AQuick Check:
Depends needs function, not function call [OK]
- Calling dependency functions inside Depends()
- Confusing async usage with dependency errors
- Ignoring Depends syntax rules
Solution
Step 1: Understand sub-dependency usage in main dependency
FastAPI allows multiple dependencies by declaring parameters with Depends(). To use two sub-dependencies, declare both as parameters with Depends().Step 2: Evaluate options for correctness
Define two sub-dependency functions, then in main dependency use Depends() for both as parameters correctly describes this pattern. Call both sub-dependencies inside main dependency without Depends() misses Depends(), so sub-dependencies won't be injected. Use a single sub-dependency that returns a tuple of both results is possible but less clear and not standard. Pass sub-dependencies as global variables to main dependency is incorrect as global variables don't work for dependency injection.Final Answer:
Define two sub-dependency functions, then in main dependency use Depends() for both as parameters -> Option DQuick Check:
Multiple Depends parameters call multiple sub-dependencies [OK]
- Calling sub-dependencies directly without Depends
- Trying to pass sub-dependencies as globals
- Combining sub-dependencies into one without clear structure
