What is Dependency Injection in FastAPI: Simple Explanation and Example
FastAPI, dependency injection is a way to provide components or resources (like database connections or services) to your path operation functions automatically. It uses the Depends function to declare dependencies, making your code cleaner and easier to test.How It Works
Dependency injection in FastAPI works like a helpful assistant who brings you the tools you need exactly when you ask for them. Instead of creating or managing resources inside your function, you just say what you need, and FastAPI provides it for you.
Imagine you are cooking and you ask a friend to hand you the salt and pepper. You don’t have to get up and find them yourself; your friend brings them to you. Similarly, FastAPI uses the Depends function to know what your function needs and supplies those dependencies automatically.
This makes your code simpler and more organized because each part focuses on its job without worrying about how to get the resources it needs.
Example
This example shows how to use dependency injection in FastAPI to provide a simple function as a dependency to a path operation.
from fastapi import FastAPI, Depends app = FastAPI() def get_message(): return "Hello from dependency!" @app.get("/") async def read_root(message: str = Depends(get_message)): return {"message": message}
When to Use
Use dependency injection in FastAPI when you want to keep your code clean and reusable. It is especially helpful for:
- Sharing common resources like database sessions or authentication logic across multiple routes.
- Making your code easier to test by replacing dependencies with mocks or stubs.
- Separating concerns so each function focuses on its main task without managing setup or cleanup.
For example, if your app needs to access a database in many places, you can create a dependency that provides a database connection. FastAPI will handle giving that connection to any route that needs it.
Key Points
- Dependency injection in FastAPI uses the
Dependsfunction to declare what a function needs. - It helps keep code clean, organized, and easy to test.
- Dependencies can be simple functions or complex classes providing resources.
- FastAPI automatically manages calling dependencies and passing their results.
Key Takeaways
Depends to provide resources automatically to functions.