FastAPI Injectable¶
Use FastAPI's Depends() anywhere - even outside FastAPI routes
Installation: pip install fastapi-injectable
Documentation: https://fastapi-injectable.readthedocs.io/en/latest/
Basic Example¶
from typing import Annotated
from fastapi import Depends
from fastapi_injectable import injectable
class Database:
def query(self) -> str:
return "data"
def get_db() -> Database:
return Database()
@injectable
def process_data(db: Annotated[Database, Depends(get_db)]) -> str:
return db.query()
# Use it anywhere!
result = process_data()
print(result) # Output: 'data'
Key Features¶
Flexible Injection: Use decorators, function wrappers, or utility functions.
Full Async Support: Works with both sync and async code.
Resource Management: Built-in cleanup for dependencies.
Dependency Caching: Optional caching for better performance.
Graceful Shutdown: Automatic cleanup on program exit.
Overview¶
fastapi-injectable is a lightweight package that enables seamless use of FastAPI’s dependency injection system outside of route handlers. It solves a common pain point where developers need to reuse FastAPI dependencies in non-FastAPI contexts like CLI tools, background tasks, or scheduled jobs, allowing you to use FastAPI’s dependency injection system anywhere!
Requirements¶
Python
3.10or higherFastAPI
0.112.4or higher