fastapi-standalone-di¶
Use FastAPI's dependency injection outside of any web/ASGI context.
FastAPI ships a powerful dependency injection system — Depends, sub-dependencies,
yield teardown, per-resolution caching. It is, however, tightly coupled to the
request/response cycle. fastapi-standalone-di reuses that exact machinery
(get_dependant, the same resolution rules) so you can resolve and invoke your
dependencies from plain Python: CLI scripts, workers, cron jobs, tests — no HTTP
server required.
Install¶
Or add it to your project with uv:
Requirements:
- Python ≥ 3.12
- FastAPI ≥ 0.61
Quick start¶
Resolve any callable that uses Depends(), exactly as FastAPI would:
import asyncio
from fastapi import Depends
from fastapi_standalone_di import FastAPIContainer
def get_settings() -> dict[str, str]:
return {"db_url": "postgres://localhost/app"}
class Database:
def __init__(self, settings: dict[str, str] = Depends(get_settings)) -> None:
self.url = settings["db_url"]
async def main() -> None:
# Explicit lifetime: create the container, then close it when done.
container = FastAPIContainer()
db = await container.get(Database)
print(db.url) # postgres://localhost/app
await container.aclose()
# Or as an async context manager (auto-closes, runs any yield teardown):
async with FastAPIContainer() as container:
db = await container.get(Database)
print(db.url)
asyncio.run(main())
The container exposes a small surface:
container.get(dep)— resolve one dependency and return its instance.container.optional(dep)— likeget, but returnsNonewhen not resolved.container.resolve(a, b, ...)— resolve several; returns aResolvedDependenciesyou query with.get(dep)/.optional(dep).container.invoke(fn)— resolvefn'sDepends()parameters and call it (entry point, not cached).container.invoke_resolved(fn)— likeinvoke, but returns aResolvedDependenciesexposing the sub-dependencies too.container.scope()— open a short-lived scope (see Usage).
Read on¶
- Usage — resolving outside ASGI, caching,
yieldteardown, overrides, registrable interfaces, application state, and dependency scopes. - Parameters & connection — supplying query/path/header/cookie
values, the standalone
Request,Response,BackgroundTasksandSecurityScopes. - API reference — every public symbol, its signature and behaviour.
Support¶
This project is hosted on GitHub. Feel free to open an issue if you think you have found a bug or something is missing.
License¶
fastapi-standalone-di is licensed under the
MIT license.