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]— resolveTby calling it, same as FastAPI'sAnnotated[T, Depends()].DepFactory[T, factory]— resolveTvia a factory, same asAnnotated[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 injectvalue, even when it is itself callable.FactoryOverride(factory)— callfactoryto 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)— whethertpis aDep/DepFactoryannotation.unwrap_dep_tp(tp)— the annotated type (Anyfor a bareDep).unwrap_dep_dependency(tp)— the callable that resolves it: the factory forDepFactory[T, factory], the type itself forDep[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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_injected-0.2.1.tar.gz.
File metadata
- Download URL: fastapi_injected-0.2.1.tar.gz
- Upload date:
- Size: 47.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via:
uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
50781b180336ba9a28aa6d7c0c8ee8a47b2a28d542bcc4c0c0f4ab385a86983e
|
|
| MD5 |
a0fd793dcd938e56f53a212a1441f276
|
|
| BLAKE2b-256 |
9d6a81a1f0efd419466f9cf1ea0afe9d4874705432b35a8ee1acbefc7e142ab9
|
File details
Details for the file fastapi_injected-0.2.1-py3-none-any.whl.
File metadata
- Download URL: fastapi_injected-0.2.1-py3-none-any.whl
- Upload date:
- Size: 12.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via:
uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d77786ef7819a2ea15b1f8577ae39ab1a996cea5cef8b1c11a5192af8256fb52
|
|
| MD5 |
18737f8cc0d2f2147bb3a42c9801f676
|
|
| BLAKE2b-256 |
1400a4ca077909fae9e8edd3b77e03039aa2653ba0e5ef6a7203319b063906df
|