Skip to main content

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, Injected, 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] = Injected) -> 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.
  • Injected — 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] = Injected) -> int:
    ...


result = await add(1, 2)

Resolving a type directly

No decorator needed — resolve a dependency graph on demand:

from fastapi_injected import resolve

service = await resolve(Service)

Like @inject, resolve accepts new_scope=True to force a fresh scope instead of reusing the surrounding one.

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.

Overriding dependencies

push_overrides swaps dependencies out for the duration of a with block — handy in tests, or anywhere you need to run the same code against a different implementation:

from fastapi_injected import push_overrides

with push_overrides({Session: Session(closed=True)}):
    await handler()  # gets the override instead of the real dependency

A key can be the dependency itself, or the annotation you wrote in the signature — Dep[Session] and DepFactory[Session, session_dep] both work and are normalized to the same underlying dependency:

with push_overrides({DepFactory[Session, session_dep]: my_session}):
    ...

Values are used as-is, but two wrappers make the intent explicit and cover the ambiguous cases:

  • ValueOverride(value) — always inject value, even when it is itself callable.
  • FactoryOverride(factory) — call factory to produce the value. Sync, async, and generator factories are all supported, with the same teardown semantics as regular dependencies.
from fastapi_injected import FactoryOverride, ValueOverride

with push_overrides(
    {
        Session: ValueOverride(fake_session),
        Repository: FactoryOverride(lambda: FakeRepository()),
    },
):
    ...

Overrides apply to the whole graph, not just top-level parameters — overriding a nested dependency changes what its dependents receive. Nested push_overrides blocks merge, with the innermost one winning.

Because the surrounding scope caches resolved dependencies, an override pushed after something has already been built would silently have no effect. To catch that, push_overrides raises NonFreshScopeError if the current scope already holds cached dependencies. Pass require_fresh_scope=False if you know what you are doing and want the override to apply only to what has not been resolved yet:

async with push_inject_scope():
    await handler()  # dependencies cached here

    with push_overrides({Session: fake}):  # raises NonFreshScopeError
        ...

Inspecting annotations

A few helpers are exported for code that needs to reason about Dep[...] annotations — building override maps, custom decorators, and the like:

  • is_dep(tp) — whether tp is a Dep/DepFactory annotation.
  • unwrap_dep_tp(tp) — the annotated type (Any for a bare Dep).
  • unwrap_dep_dependency(tp) — the callable that resolves it: the factory for DepFactory[T, factory], the type itself for Dep[T].

FastAPI request integration

Inside a FastAPI app, @inject-ed functions and resolve can share the request's own dependency cache — the same instances FastAPI built for the handler. Register init_inject_scope as a dependency:

from fastapi import Depends, FastAPI
from fastapi_injected import Dep, init_inject_scope, resolve

app = FastAPI(dependencies=[Depends(init_inject_scope)])


@app.get("/")
async def route(service: Dep[Service]) -> str:
    same = await resolve(Service)  # same instance as `service`
    ...

Anything called from the handler — including @inject-ed helpers — resolves against the request's cache, so a per-request dependency like a DB session stays a single instance for the whole request.

License

MIT

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.2.0.tar.gz (43.0 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.2.0-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fastapi_injected-0.2.0.tar.gz
  • Upload date:
  • Size: 43.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","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.2.0.tar.gz
Algorithm Hash digest
SHA256 b475badd056696ab2eb4ca76b0ede7277377d788d94f14de31617f340db09143
MD5 3a99ee52c033faa6d147f84423c86623
BLAKE2b-256 4c9b40faae01524454347192a82ceea603a5d8adb637aa0c39e095f8c59f33b5

See more details on using hashes here.

File details

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

File metadata

  • Download URL: fastapi_injected-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 11.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","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.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6d178601245735d7612b67b430a8f043a0a94b028ea3f16b1f42d4184c413d6c
MD5 1c7d030ce7e0ddfeac5c58628fcaddea
BLAKE2b-256 249140f153685b399790b2db8477122a3b71c6fe1a608b78b83d40f8ffe78437

See more details on using hashes here.

Release history Release notifications | RSS feed

0.3.3

2 files

0.3.2

2 files

0.3.1

2 files

0.3.0

2 files

0.2.2

2 files

0.2.1

2 files

This release

0.2.0 This release

2 files

0.1.4

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page