Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 Middleware📚 Background Tasks📚 WebSockets📚 CORS📚 Dependencies📚 Dependency Injection📚 Async Programming📚 Performance
Fastapi/Advanced Patterns/Dependency Injection

Dependency Injection

Learn the fundamentals of dependency injection in FastAPI.

🎯 Core Concept

Dependency Injection (DI) decouples your code by injecting required objects rather than creating them inside functions. FastAPI's `Depends()` enables powerful, reusable dependency chains that automatically resolve and inject parameters.

📖 What You'll Learn

In this section, you'll understand:

  • How `Depends()` enables dependency injection
  • Creating injectable dependency functions
  • Dependency sub-dependencies (chaining)
  • Injecting complex objects (configs, services)
  • Testability through dependency replacement

💡 Basic Dependency Injection

from fastapi import FastAPI, Depends

app = FastAPI()

# Simple dependency
def get_db_connection():
    connection = SomeDatabase()
    try:
        yield connection
    finally:
        connection.close()

# Injected into endpoint
@app.get("/data")
async def get_data(db = Depends(get_db_connection)):
    data = db.query("SELECT * FROM items")
    return data

Parameterized Dependencies

def get_current_user(token: str = Header(...)):
    # Dependency receives parameters from request
    user = verify_token(token)
    if not user:
        raise HTTPException(status_code=401)
    return user

def get_admin_user(user = Depends(get_current_user)):
    # Sub-dependency: depends on another dependency
    if user.role != "admin":
        raise HTTPException(status_code=403)
    return user

@app.delete("/users/{user_id}")
async def delete_user(user_id: int, admin = Depends(get_admin_user)):
    # Only accessible to admins
    return {"deleted": user_id}

Service Injection Pattern

class UserService:
    def __init__(self, db: Session):
        self.db = db

    def get_user(self, user_id: int):
        return self.db.query(User).filter(User.id == user_id).first()

def get_user_service(db = Depends(get_db)):
    return UserService(db)

@app.get("/users/{user_id}")
async def get_user(user_id: int, service = Depends(get_user_service)):
    user = service.get_user(user_id)
    return user

Testing with Dependency Overrides

# Production
def get_db():
    return ProductionDatabase()

# Test setup
from fastapi.testclient import TestClient

def override_get_db():
    return MockDatabase()

app.dependency_overrides[get_db] = override_get_db

# Now tests use mock database
client = TestClient(app)
response = client.get("/data")

Real-World Usage

DI enables:

  • **Testability**: Replace real implementations with mocks
  • **Reusability**: Share logic across multiple endpoints
  • **Cleanliness**: Separate concerns and dependencies
  • **Flexibility**: Change implementations without changing endpoints
  • **Configuration**: Inject different configs per environment

🔑 Key Takeaways

  • ✅ Understand the purpose of dependency injection
  • ✅ Know when to apply this pattern
  • ✅ Recognize its benefits in real-world scenarios
  • ✅ Be prepared to use it in your projects

Ready to explore more? Check out the advanced section for production patterns and edge cases.


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn