0
0
FastAPIframework~5 mins

Sub-dependencies in FastAPI

Choose your learning style9 modes available
Introduction

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.

When you have a common piece of logic needed by multiple dependencies.
When you want to break down complex dependencies into smaller, simpler parts.
When you want to share authentication or database connection logic across different routes.
When you want to keep your code DRY (Don't Repeat Yourself) by reusing dependency functions.
Syntax
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.

Examples
This example shows a sub-dependency get_token used inside verify_token to check a token.
FastAPI
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
Here, get_db is a sub-dependency that provides a database connection to get_user.
FastAPI
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}"
Sample Program

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.

FastAPI
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
OutputSuccess
Important Notes

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.

Summary

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.