Skip to main content

modern-di-fastapi

PyPI version Supported Python versions Downloads Coverage CI License GitHub stars uv Ruff ty

modern-di integration for FastAPI.

Full guide: FastAPI integration docs

Usage example: fastapi-sqlalchemy-template

Installation

uv add modern-di-fastapi      # or: pip install modern-di-fastapi

Usage

setup_di stores the container on the app and opens and closes it with the app lifespan. FromDI resolves a provider (or type) into a route parameter. It builds the per-connection child container on demand through Depends(build_di_container), so only routes that use FromDI get one.

import dataclasses

import fastapi
from modern_di import Container, Group, Scope, providers
from modern_di_fastapi import FromDI, setup_di


@dataclasses.dataclass(kw_only=True)
class Settings:
    debug: bool = True


@dataclasses.dataclass(kw_only=True)
class UserService:
    settings: Settings  # auto-injected by type


class Dependencies(Group):
    settings = providers.Factory(scope=Scope.APP, creator=Settings)
    user_service = providers.Factory(scope=Scope.REQUEST, creator=UserService)


app = fastapi.FastAPI()
container = Container(groups=[Dependencies])
setup_di(app, container)
container.validate()  # optional fail-fast; must come after setup_di registers its providers


@app.get("/")
async def index(user_service: UserService = FromDI(Dependencies.user_service)) -> dict[str, bool]:
    return {"debug": user_service.settings.debug}

The framework Request / WebSocket are resolvable within DI via the pre-built fastapi_request_provider / fastapi_websocket_provider context providers.

An app mounted under another with app.mount can call setup_di with its own container, and its routes resolve from that container. Starlette runs only the outermost app's lifespan, so the outer app's lifespan also opens and closes the root container of every mounted app that called setup_di, including apps under Host routes and apps mounted more than one level deep. It looks for them at startup, so mounts added after setup_di are included. Each container is opened once and closed at shutdown, after your lifespan code. The mounted app's own lifespan function still does not run.

API

Symbol Description
setup_di(app, container) Stores the container on app.state and composes the container's open/close into the app lifespan (nesting inside any existing lifespan=)
FromDI(dependency, *, use_cache=True) FastAPI Depends that resolves a provider (or type) from the per-connection child container. Raises RuntimeError naming setup_di when a request reaches it without setup_di called
fetch_di_container(app) Returns the app-scoped container from app.state. Raises RuntimeError naming setup_di when called without setup_di called
build_di_container(connection) FastAPI Depends callable that yields the per-connection child container: REQUEST scope for an HTTP request, SESSION scope for a WebSocket
fastapi_request_provider ContextProvider for the current fastapi.Request (REQUEST scope)
fastapi_websocket_provider ContextProvider for the current fastapi.WebSocket (SESSION scope)

📦 PyPI

📝 License

Part of modern-python

Built on modern-di, a dependency-injection framework with an IoC container and scopes.

Browse the full list of templates and libraries in modern-python; the org profile has the categorized index.

Metadata

Release files for modern-di-fastapi 4.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for modern-di-fastapi 4.0.1
File Size Uploaded Provenance
modern_di_fastapi-4.0.1.tar.gz 5.7 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for modern-di-fastapi 4.0.1
File Interpreter ABI Platform
modern_di_fastapi-4.0.1-py3-none-any.whl Python 3 none any Details

Total release size: 11.4 kB

Release files / modern_di_fastapi-4.0.1.tar.gz

Download URL modern_di_fastapi-4.0.1.tar.gz
Size 5.7 kB
Tags Source
SHA-256 checksum
How to use checksums
cbae53929cd0cf7c519023e227ac5cf219335d5b1eacc1bdb6590a72ad1ad5cd
BLAKE2b-256 checksum
How to use checksums
f82cba32d9b745b044134a1e69d5d0652ae04bb4878bfb9b181107207b129de3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","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}

Release files / modern_di_fastapi-4.0.1-py3-none-any.whl

Download URL modern_di_fastapi-4.0.1-py3-none-any.whl
Size 5.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0415dd8d0ee2ce54d0de4a8c52b35f821a6a137fe5ecf74521b844e106b08a33
BLAKE2b-256 checksum
How to use checksums
8f372d1f8a3251878dc2f051dd4f801933986f2ec3d6fe208b4650c0d97c049f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","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}

Security for modern-di-fastapi 4.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

4.0.1 This release

2 release files No provenance

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