Showing posts with label Backend Development. Show all posts
Showing posts with label Backend Development. Show all posts

Monday, 22 December 2025

FastAPI Dependency Injection Explained with Examples

Dependency Injection (DI) is one of the most powerful features of FastAPI, yet it’s also one of the most confusing topics for beginners.

If you are coming from Spring Boot, you may think:

“Where is @Autowired in FastAPI?”

In this post, we’ll explain FastAPI Dependency Injection in simple terms, with real-world examples and best practices.


What Is Dependency Injection?

Dependency Injection means:

Passing required objects (dependencies) into a function instead of creating them inside the function.

Why it matters

  • Cleaner code

  • Better reusability

  • Easier testing

  • Loose coupling


Dependency Injection in FastAPI

FastAPI provides dependency injection using the Depends() function.

It allows you to:

  • Inject database connections

  • Inject authentication logic

  • Inject services

  • Share common logic across APIs


Basic Dependency Injection Example

Simple dependency function

from fastapi import Depends def get_message(): return "Hello from dependency"

Using it in an API

from fastapi import FastAPI, Depends app = FastAPI() @app.get("/hello") def hello(message: str = Depends(get_message)): return {"message": message}

📌 FastAPI automatically:

  • Calls get_message()

  • Injects the returned value

  • Manages execution order


Dependency Injection vs Normal Function Call

❌ Without DI:

@app.get("/users") def get_users(): db = create_db_connection() return db.fetch_users()

✅ With DI:

def get_db(): return create_db_connection() @app.get("/users") def get_users(db = Depends(get_db)): return db.fetch_users()

✔ Cleaner
✔ Reusable
✔ Test-friendly


Real-World Example: Database Dependency

Database session dependency

def get_db(): db = DBSession() try: yield db finally: db.close()

Injecting DB into API

@app.get("/users") def get_users(db = Depends(get_db)): return db.get_all_users()

📌 FastAPI handles:

  • Opening the DB

  • Closing the DB

  • Exception safety


Dependency Injection for Authentication

Auth dependency

def get_current_user(token: str = Depends(oauth2_scheme)): return decode_jwt(token)

Protected API

@app.get("/profile") def profile(user = Depends(get_current_user)): return user

✔ Auth logic is reusable
✔ APIs stay clean


Dependency Injection for Services (Spring Boot Style)

Service class

class UserService: def get_users(self): return ["Alice", "Bob"]

Dependency provider

def get_user_service(): return UserService()

API using service

@app.get("/users") def users(service: UserService = Depends(get_user_service)): return service.get_users()

📌 This is similar to:

@Autowired UserService userService;

Dependency Injection with Parameters

Dependencies can also accept parameters:

def common_params(limit: int = 10, offset: int = 0): return {"limit": limit, "offset": offset} @app.get("/items") def get_items(params = Depends(common_params)): return params

Great for:

  • Pagination

  • Filters

  • Query parameters


Nested Dependencies

Dependencies can depend on other dependencies:

def get_db(): ... def get_user(db = Depends(get_db)): ...

FastAPI resolves them automatically.


Dependency Injection for Testing (Huge Benefit)

Override dependency in tests

app.dependency_overrides[get_db] = get_test_db

✔ No real DB
✔ Faster tests
✔ Cleaner test setup


Common Use Cases for Dependency Injection in FastAPI

✅ Database sessions
✅ Authentication & authorization
✅ API keys
✅ Logging
✅ Configuration
✅ Feature flags


Common Mistakes to Avoid

❌ Creating DB connections inside endpoints
❌ Writing auth logic repeatedly
❌ Mixing business logic in controllers
❌ Not using DI for shared logic


FastAPI DI vs Spring Boot DI

FeatureFastAPISpring Boot
DI StyleFunction-basedAnnotation-based
Learning curveEasyMedium
FlexibilityVery highStructured
BoilerplateLowHigh

FastAPI DI is lighter, while Spring DI is more structured.


Best Practices

✔ Keep dependencies small
✔ Use DI for cross-cutting concerns
✔ Avoid heavy logic in endpoints
✔ Use DI for better testing
✔ Name dependencies clearly


Final Thoughts

FastAPI’s Dependency Injection system is:

  • Simple

  • Powerful

  • Pythonic

  • Production-ready

Once you master Depends(), your FastAPI code becomes:

  • Cleaner

  • More maintainable

  • Easier to scale


Suggested Next Reads

  • FastAPI Project Structure Best Practices

  • FastAPI Microservices Setup

  • FastAPI Authentication with JWT

  • FastAPI Interview Questions