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.
Event Loop Management: Control the event loop to ensure the objects created by
fastapi-injectableare executed in the right loop.
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
Frequently Asked Questions¶
Why not directly use other DI packages like Dependency Injector or FastDepends?
What happens to dependency cleanup in long-running processes?
Are type hints fully supported for
injectable()andget_injected_obj()?
Why would I need this package?¶
A: If your project heavily relies on FastAPI’s Depends() as the sole DI system and you don’t want to introduce additional DI packages (like Dependency Injector or FastDepends), fastapi-injectable is your friend.
It allows you to reuse your existing FastAPI built-in DI system anywhere, without the need to refactor your entire codebase or maintain multiple DI systems.
Life is short, keep it simple!
Why not directly use other DI packages like Dependency Injector or FastDepends?¶
A: You absolutely can if your situation allows you to:
Modify large amounts of existing code that uses
Depends()Maintain multiple DI systems in your project
fastapi-injectable focuses solely on extending FastAPI’s built-in Depends() beyond routes. We’re not trying to be another DI system - we’re making the existing one more useful!
For projects with hundreds of dependency functions (especially with nested dependencies), this approach is more intuitive and requires minimal changes to your existing code.
Choose what works best for you!
Can I use it with existing FastAPI dependencies?¶
A: Absolutely! That’s exactly what this package was built for! fastapi-injectable was created to seamlessly work with FastAPI’s dependency injection system, allowing you to reuse your existing Depends() code anywhere - not just in routes.
Focus on what matters instead of worrying about how to get your existing dependencies outside of FastAPI routes!
Does it work with all FastAPI dependency types?¶
A: Yes! It supports:
Regular dependencies
Generator dependencies (with cleanup utility functions)
Async dependencies
Sync dependencies
Nested dependencies (dependencies with sub-dependencies)
What happens to dependency cleanup in long-running processes?¶
A: You have three options:
Manual cleanup per function:
await cleanup_exit_stack_of_func(your_func)Cleanup everything:
await cleanup_all_exit_stacks()Automatic cleanup on shutdown:
setup_graceful_shutdown()
Can I mix sync and async dependencies?¶
A: Yes! You can freely mix them. For running async code in sync contexts, use the provided run_coroutine_sync() utility.
Are type hints fully supported for injectable() and get_injected_obj()?¶
A: Currently, type hint support is a work in progress. However, this doesn’t affect the core benefits of the package (seamlessly reusing and maintaining consistency in your FastAPI DI system).
We’re actively working on improving type hint support, and we’ll have good news on this front soon! In the meantime, enjoy the elegant and clean solution that fastapi-injectable provides.
How does caching work?¶
A: By default, dependencies are cached like in FastAPI routes. You can disable caching with @injectable(use_cache=False) if you need fresh instances.
Is it production-ready?¶
A: Yes! The package has:
100% test coverage
Type checking with
mypyComprehensive error handling
Production use cases documented