I created fastapi-injectable to solve a common pain point in FastAPI: using Depends() outside of route handlers. This has been a long-standing issue in the FastAPI community with a discussion post around it.
Install with: pip install fastapi-injectable
The package lets you use FastAPI's dependency injection in:
- CLI tools
- Background workers
- Test fixtures
- Any non-HTTP context
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'
This is a production-ready package for FastAPI developers who need to use dependency injection outside of HTTP routes.The common suggestion for handling dependencies outside FastAPI routes is to use separate DI frameworks like dependency-injector. However, this means:
1. Managing two different DI systems in your codebase
2. Learning another framework's patterns
3. Potentially duplicating dependency logic
Currently, there's no package that extends FastAPI's native Depends() beyond routes.
fastapi-injectable solves this by providing a clean API that lets you use FastAPI's dependency injection anywhere.
Links:
GitHub: https://github.com/your-username/fastapi-injectable
Docs: https://fastapi-injectable.readthedocs.io
PyPI: https://pypi.org/project/fastapi-injectable
I'd love to hear your feedback and contributions to make this package better! Feel free to open issues or PRs if you have ideas for improvements.