Skip to main content

Yet another library to reuse fastapi dependency injection

Project description

fastapi-injected

Yet another attempt to reuse FastAPI's dependency injection outside of request handlers.

This is an opinionated library: it takes the DI machinery you already know from FastAPI (Depends, generator dependencies with teardown, dependency caching) and makes it usable in plain async functions — background jobs, CLI commands, workers, scripts — without a Request in sight.

Installation

pip install fastapi-injected

Requires Python 3.12+.

Usage

Declare dependencies as regular classes and annotate fields with Dep[...]:

from dataclasses import dataclass
from typing import AsyncIterator

from fastapi_injected import Dep, DepFactory, Inejected, inject


@dataclass
class Session:
    closed: bool = False


async def session_dep() -> AsyncIterator[Session]:
    session = Session()
    try:
        yield session
    finally:
        session.closed = True


@dataclass
class Repository:
    session: DepFactory[Session, session_dep]


@dataclass
class Service:
    repo: Dep[Repository]


@inject
async def handler(*, service: Dep[Service] = Inejected) -> None:
    ...  # service is built and injected, session is closed on exit


await handler()
  • Dep[T] — resolve T by calling it, same as FastAPI's Annotated[T, Depends()].
  • DepFactory[T, factory] — resolve T via a factory, same as Annotated[T, Depends(factory)]. Generator factories get proper teardown.
  • Inejected — a sentinel default that exists purely to make type checkers happy: without it they would complain about a missing argument at call sites. At runtime the parameter is always filled in by @inject.

Injected parameters mix freely with regular ones — pass your own arguments as usual and the rest is injected:

@inject
async def add(a: int, b: int, *, service: Dep[Service] = Inejected) -> int:
    ...


result = await add(1, 2)

Solving a type directly

No decorator needed — resolve a dependency graph on demand:

from fastapi_injected import solve

service = await solve(Service)

Scopes and caching

By default every call to an injected function gets its own scope: dependencies are built, cached within the call, and torn down when it returns. Wrap several calls in push_inject_scope() to share one cache (and defer teardown to the end of the scope):

from fastapi_injected import push_inject_scope

async with push_inject_scope():
    a = await handler()  # dependencies built here
    b = await handler()  # same instances reused
# generator dependencies are torn down here

Use @inject(new_scope=True) to opt a function out of the surrounding scope and always get fresh dependencies.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_injected-0.1.1.tar.gz (36.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_injected-0.1.1-py3-none-any.whl (7.9 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_injected-0.1.1.tar.gz.

File metadata

  • Download URL: fastapi_injected-0.1.1.tar.gz
  • Upload date:
  • Size: 36.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.31 {"installer":{"name":"uv","version":"0.11.31","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for fastapi_injected-0.1.1.tar.gz
Algorithm Hash digest
SHA256 65d8cb00dee7f8e5c7b1997cfd8a241e0fe5ebe26f3af01f4c7ff358f22f3eee
MD5 89331c02bd34f0aa17d8e9b4e414dfc1
BLAKE2b-256 44e5e84d7c7dd535527868ff18db57bbb26164eb6ad17c200b3d157ceb7d195b

See more details on using hashes here.

File details

Details for the file fastapi_injected-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: fastapi_injected-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 7.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.31 {"installer":{"name":"uv","version":"0.11.31","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for fastapi_injected-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 98f985a01aec1d9b6e8cca369ebce51974b0df8361748dd19b0183de58b9949c
MD5 944035173bb3709e93e6bf4f94ebf04c
BLAKE2b-256 ee42bfd080a7c0464d07fce44185fae2faa6bda8db58114a7e94f93f64ba2591

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page