Skip to main content

modern-di-starlette

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

Modern-DI integration for Starlette.

Full guide: Starlette integration docs

Usage example: examples/

Installation

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

Usage

setup_di registers the container, composes the lifespan, and installs middleware that builds a per-connection child container. Decorate an endpoint with @inject and mark parameters with FromDI to receive resolved dependencies. Starlette has no native DI, so @inject is required (there is no Depends).

import dataclasses
import typing

from modern_di import Container, Group, Scope, providers
from modern_di_starlette import FromDI, inject, setup_di
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route


@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)


@inject
async def homepage(
    request: Request,
    service: typing.Annotated[UserService, FromDI(Dependencies.user_service)],
) -> JSONResponse:
    return JSONResponse({"debug": service.settings.debug})


app = Starlette(routes=[Route("/", homepage)])
container = Container(groups=[Dependencies])
setup_di(app, container)
container.validate()  # optional fail-fast; must come after setup_di registers its providers

Call setup_di once, after creating the app and before it starts serving — it installs middleware, and Starlette does not allow middleware to be added after startup.

@inject works the same on the methods of a class-based endpoint. Decorate the handler method, not the class; self and any arguments Starlette passes after the connection are forwarded unchanged, so WebSocketEndpoint.on_receive and on_disconnect inject too:

from starlette.endpoints import HTTPEndpoint, WebSocketEndpoint
from starlette.routing import Route, WebSocketRoute
from starlette.websockets import WebSocket


class Users(HTTPEndpoint):
    @inject
    async def get(
        self,
        request: Request,
        service: typing.Annotated[UserService, FromDI(Dependencies.user_service)],
    ) -> JSONResponse:
        return JSONResponse({"debug": service.settings.debug})


class Echo(WebSocketEndpoint):
    encoding = "text"

    @inject
    async def on_receive(
        self,
        websocket: WebSocket,
        data: str,
        service: typing.Annotated[UserService, FromDI(Dependencies.user_service)],
    ) -> None:
        await websocket.send_text(data)


app = Starlette(routes=[Route("/users", Users), WebSocketRoute("/echo", Echo)])

An HTTP request opens a Scope.REQUEST child container; a WebSocket connection opens a Scope.SESSION one, both built by the middleware before your handler runs. The connection starlette.requests.Request / starlette.websockets.WebSocket are resolvable within DI via the pre-built starlette_request_provider / starlette_websocket_provider context providers. The instance a provider receives is backed by the same ASGI scope as your handler's connection but is a distinct object: read method / url / headers / state from it, not the request body.

API

Symbol Description
setup_di(app, container) Registers the container on app.state, composes the lifespan (opens/closes the container), and installs the middleware that builds a per-connection child container; returns the container
FromDI(dependency) Inert marker (used with @inject) that resolves a provider or type from the per-connection child container
inject(handler) Decorator for an async def handler taking a Request or WebSocket, either a function endpoint or a method of an HTTPEndpoint / WebSocketEndpoint subclass; resolves its FromDI-annotated parameters
fetch_di_container(app) Returns the root Container stored on app.state
starlette_request_provider ContextProvider for starlette.requests.Request (REQUEST scope), auto-registered
starlette_websocket_provider ContextProvider for starlette.websockets.WebSocket (SESSION scope), auto-registered

📦 PyPI

📝 License

Part of modern-python

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

Browse the full list of templates and libraries in modern-python — see the org profile for the categorized index.

Metadata

Release files for modern-di-starlette 3.2.0

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-starlette 3.2.0
File Size Uploaded
modern_di_starlette-3.2.0.tar.gz 5.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for modern-di-starlette 3.2.0
File Interpreter ABI Platform
modern_di_starlette-3.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 11.8 kB

Release files / modern_di_starlette-3.2.0.tar.gz

Download URL modern_di_starlette-3.2.0.tar.gz
Size 5.7 kB
Tags Source
SHA-256 checksum
How to use checksums
aca56158ab2be6ffa769a9f0e005c06e18309874a4f4a86f4c84864bc4f86a82
BLAKE2b-256 checksum
How to use checksums
f997b189cfa3afb16b30a22a023978c065b8e5de2c35979d99e8eb259656540b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.15 {"installer":{"name":"uv","version":"0.12.15","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_starlette-3.2.0-py3-none-any.whl

Download URL modern_di_starlette-3.2.0-py3-none-any.whl
Size 6.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7e7dd99bed3334307c88febf3f513f4c45e5ff7efd2ce3b7d08d6879a3562a4b
BLAKE2b-256 checksum
How to use checksums
b659b666297d98f805f9531fe4300e81714bbe9d9749b96eeee7aa7b26fcf20c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.15 {"installer":{"name":"uv","version":"0.12.15","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 history Release notifications | RSS feed

3.3.0

2 release files

This release

3.2.0 This release

2 release files

3.1.1

2 release files

3.1.0

2 release files

3.0.0

2 release files

2.2.0

2 release files

2.1.0

2 release files

2.0.0

2 release 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