FastAPI Injectable

FastAPI Injectable

Use FastAPI's Depends() anywhere - even outside FastAPI routes

PyPI Python Version License Read the documentation

CI Codecov Ruff Mypy pre-commit


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

  1. Flexible Injection: Use decorators, function wrappers, or utility functions.

  2. Full Async Support: Works with both sync and async code.

  3. Resource Management: Built-in cleanup for dependencies.

  4. Dependency Caching: Optional caching for better performance.

  5. 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.10 or higher

  • FastAPI 0.112.4 or higher