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
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.