Skip to main content

Dependency Injection in FastAPI

Following our lesson on Status Codes and Error Handling in Web APIs, this article explores Dependency Injection in FastAPI. This is one of FastAPI's most powerful features, allowing you to manage dependencies and reuse code in a simple and elegant way.


📚 Prerequisites

  • A running FastAPI application.
  • Understanding of Python functions.

🎯 Article Outline: What You'll Master

  • Foundational Theory: What Dependency Injection is.
  • Core Implementation: Using Depends to inject dependencies.
  • Practical Application: Creating a common dependency for database connections or authentication.
  • Classes as Dependencies: Using classes as dependencies.

🧠 Section 1: The Core Concepts of Dependency Injection

Dependency Injection is a design pattern where the dependencies of a component (e.g., a function or a class) are provided to it, rather than the component creating them itself. In FastAPI, this means you can have functions that your path operation functions "depend" on. FastAPI will take care of calling these dependency functions and passing their return values to your path operation function.


💻 Section 2: Deep Dive - Implementation and Walkthrough

Let's see how to use Depends.

# main.py
from fastapi import Depends, FastAPI, Header, HTTPException
from typing import Optional

app = FastAPI()

async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}

@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return commons

@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters)):
return commons

Step-by-Step Code Breakdown:

  1. async def common_parameters(...): This is our dependency function. It takes some common query parameters.
  2. commons: dict = Depends(common_parameters): In our path operation functions, we use Depends to declare the dependency. FastAPI will call common_parameters and pass its return value as the commons argument.
  3. Now, both /items/ and /users/ can reuse the same pagination logic without duplicating code.

🛠️ Section 3: Classes as Dependencies

You can also use classes as dependencies. FastAPI will call the class, creating a new instance, and pass that instance to your path operation function.

# main.py (continued)
class CommonQueryParams:
def __init__(self, q: Optional[str] = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit

@app.get("/things/")
async def read_things(commons: CommonQueryParams = Depends(CommonQueryParams)):
return commons

💡 Conclusion & Key Takeaways

You've learned how to use FastAPI's powerful dependency injection system to share code and manage dependencies between your path operations.

Let's summarize the key takeaways:

  • Dependency Injection is a powerful pattern for code reuse and separation of concerns.
  • FastAPI's Depends makes it easy to implement.
  • You can create dependencies that are functions or classes.

➡️ Next Steps

In the next article, "CORS (Cross-Origin Resource Sharing) in FastAPI APIs", we'll learn how to allow web applications from other domains to access our API.


Glossary

  • Dependency Injection: A design pattern where a component's dependencies are provided to it.
  • Depends: A FastAPI utility for declaring dependencies.

Further Reading