Dependency Injection in FastAPI (Depends)

 

Introduction

As your API grows, you’ll start repeating code like:

  • Database connections
  • Authentication checks
  • Common validations 

Instead of duplicating logic everywhere, FastAPI provides a powerful feature called Dependency Injection using Depends().This helps you write clean, reusable, and maintainable code.

What is Dependency Injection?

Dependency Injection (DI) means:

Providing required functionality (dependencies) to a function instead of writing it inside the function.

Why Use Dependency Injection?

Without DI:

  • Code duplication
  • Hard to maintain
  • Difficult to test

With DI:

  • Reusable logic
  • Cleaner code
  • Better structure

Basic Example

from fastapi import FastAPI, Depends

app = FastAPI()

def common_function():
return {"message": "This is a dependency"}

@app.get("/")
def home(data: dict = Depends(common_function)):
return data

common_function is injected into the route automatically.

How Depends() Works

  • FastAPI calls the dependency function
  • Gets the result
  • Passes it to your route function 

Real-World Example: Authentication

from fastapi import HTTPException, Depends

def get_current_user(token: str = "fake-token"):
if token != "secret":
raise HTTPException(status_code=401, detail="Unauthorized")
return {"user": "admin"}

@app.get("/dashboard")
def dashboard(user: dict = Depends(get_current_user)):
return {"message": "Welcome", "user": user}

Database Dependency Example

def get_db():
db = "Database Connection"
try:
yield db
finally:
print("Closing DB connection")

@app.get("/items")
def get_items(db = Depends(get_db)):
return {"db": db}

yield is used for setup & cleanup.

Multiple Dependencies

def dep1():
return "Dependency 1"

def dep2():
return "Dependency 2"

@app.get("/multi")
def multi(d1: str = Depends(dep1), d2: str = Depends(dep2)):
return {"d1": d1, "d2": d2}

Organizing Dependencies (Best Practice)

app/dependencies/auth.py

def get_current_user():
return {"user": "admin"}

routes

from app.dependencies.auth import get_current_user

Dependency Types

TypeUse Case
Function     Common logic
Class     Complex logic
Yield dependency     DB/session handling

Common Mistakes

1. Writing all logic inside routes
2. Not using Depends() for reusable code
3. Forgetting cleanup in DB connections
4. Overcomplicating simple dependencies

Key Takeaways

  • Depends() enables dependency injection in FastAPI
  • Helps reuse logic across routes
  • Ideal for authentication, DB, validation
  • Makes code clean and scalable

Comments

Popular posts from this blog

Database Integration in FastAPI (SQLAlchemy CRUD)

Middleware & CORS in FastAPI

Python Data Handling