How to Use Class as Dependency in FastAPI: Simple Guide
Depends to inject it into your path operation functions. FastAPI will create an instance of the class and pass it automatically where needed.Syntax
To use a class as a dependency in FastAPI, define a class with an __init__ method for setup. Then, use Depends() in your path operation function parameters to request an instance of that class.
FastAPI will create and manage the class instance for you.
from fastapi import FastAPI, Depends class MyDependency: def __init__(self): self.value = "Hello from class dependency" app = FastAPI() @app.get("/") async def read_root(dep: MyDependency = Depends()): return {"message": dep.value}
Example
This example shows a class Database used as a dependency. It simulates a connection setup in __init__. The get_data method returns sample data. The class instance is injected into the route handler using Depends().
from fastapi import FastAPI, Depends class Database: def __init__(self): self.connected = True def get_data(self): return {"data": "Sample data from DB"} app = FastAPI() @app.get("/data") async def read_data(db: Database = Depends()): if db.connected: return db.get_data() return {"error": "DB not connected"}
Common Pitfalls
1. Forgetting to use Depends(): If you use the class type directly without Depends(), FastAPI won't treat it as a dependency and won't create an instance.
2. Using stateful classes without care: Class instances are created per request by default. If you want to share state, consider using singletons or other patterns.
3. Not defining __init__ properly: The class must have an __init__ method if you want to initialize attributes.
from fastapi import FastAPI class WrongDependency: def __init__(self): self.value = "Won't work as dependency" app = FastAPI() @app.get("/wrong") async def wrong_route(dep: WrongDependency): # Missing Depends() return {"message": dep.value} # Correct way: from fastapi import Depends @app.get("/right") async def right_route(dep: WrongDependency = Depends()): return {"message": dep.value}
Quick Reference
- Define a class with
__init__for setup. - Use
Depends()to inject the class instance. - Instances are created per request by default.
- Use
Depends()even if no parameters are needed. - Manage shared state carefully if needed.
Key Takeaways
Depends() to inject class dependencies in FastAPI routes.__init__ method in your class to initialize it properly.Depends() even if the class has no parameters.