Metadata-Version: 2.4
Name: modern-di-starlette
Version: 4.3.2
Summary: modern-di integration for Starlette
Keywords: dependency-injection,di,ioc-container,modern-di,starlette,python
Author: Artur Shiriev
Author-email: Artur Shiriev <me@shiriev.ru>
License-Expression: MIT
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta
Classifier: Typing :: Typed
Classifier: Topic :: Software Development :: Libraries
Requires-Dist: starlette>=1.2,<2
Requires-Dist: modern-di>=4.2,<5
Requires-Python: >=3.11, <4
Project-URL: Homepage, https://modern-di.modern-python.org
Project-URL: Documentation, https://modern-di.modern-python.org/integrations/starlette/
Project-URL: Repository, https://github.com/modern-python/modern-di-starlette
Project-URL: Issues, https://github.com/modern-python/modern-di-starlette/issues
Project-URL: Changelog, https://github.com/modern-python/modern-di-starlette/releases
Description-Content-Type: text/markdown

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)"  srcset="https://raw.githubusercontent.com/modern-python/.github/main/brand/projects/modern-di-starlette/lockup-dark.svg">
    <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/modern-python/.github/main/brand/projects/modern-di-starlette/lockup-light.svg">
    <img alt="modern-di-starlette" src="https://raw.githubusercontent.com/modern-python/.github/main/brand/projects/modern-di-starlette/lockup.png" width="420">
  </picture>
</p>

[![PyPI version](https://img.shields.io/pypi/v/modern-di-starlette.svg)](https://pypi.org/project/modern-di-starlette/)
[![Supported Python versions](https://img.shields.io/pypi/pyversions/modern-di-starlette.svg)](https://pypi.org/project/modern-di-starlette/)
[![Downloads](https://static.pepy.tech/badge/modern-di-starlette/month)](https://pepy.tech/projects/modern-di-starlette)
[![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen.svg)](https://github.com/modern-python/modern-di-starlette/actions/workflows/ci.yml)
[![CI](https://github.com/modern-python/modern-di-starlette/actions/workflows/ci.yml/badge.svg)](https://github.com/modern-python/modern-di-starlette/actions/workflows/ci.yml)
[![License](https://img.shields.io/github/license/modern-python/modern-di-starlette.svg)](https://github.com/modern-python/modern-di-starlette/blob/main/LICENSE)
[![GitHub stars](https://img.shields.io/github/stars/modern-python/modern-di-starlette)](https://github.com/modern-python/modern-di-starlette/stargazers)
[![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json)](https://github.com/astral-sh/uv)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![ty](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ty/main/assets/badge/v0.json)](https://github.com/astral-sh/ty)

[modern-di](https://github.com/modern-python/modern-di) integration for [Starlette](https://www.starlette.io).

Full guide: [Starlette integration docs](https://modern-di.modern-python.org/integrations/starlette/)

Usage example: [examples/](https://github.com/modern-python/modern-di-starlette/tree/main/examples)

## Installation

```bash
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`).

```python
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` also works on a plain `def` endpoint. It returns a sync wrapper for a sync function, so Starlette still runs that endpoint in its threadpool.

`@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:

```python
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,
        settings: typing.Annotated[Settings, FromDI(Dependencies.settings)],
    ) -> None:
        await websocket.send_text(f"{data} debug={settings.debug}")


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. A WebSocket handler can therefore inject `APP`- and `SESSION`-scoped dependencies but not `REQUEST`-scoped ones. 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.

A Starlette app mounted under another with `Mount` can call `setup_di` with its own container. A route inside the mounted app then resolves from the mounted app's container, and routes outside it resolve from the outer one. Both middlewares open a child container for the connection and both close it when the connection ends. If only the outer app calls `setup_di`, routes in the mounted app resolve from the outer 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, apps mounted with `Mount(..., middleware=[...])`, 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, before your lifespan's startup code, and closed after its shutdown code. The mounted app's own lifespan function still does not run. A mounted app whose `setup_di` was called with `manage_lifespan=False` is skipped.

### Sharing a container

By default the lifespan opens the root container before your lifespan's startup code and closes it after its shutdown code, which runs its `APP`-scoped finalizers. Your startup and shutdown code can both resolve `APP`-scoped dependencies. To share one container between this app and something else that outlives it, such as a second app or a worker, pass `manage_lifespan=False` and open and close the container yourself:

```python
setup_di(app, container, manage_lifespan=False)


async def main() -> None:
    async with container:
        ...  # run the app and anything else that uses the container
```

The middleware still opens and closes a child container for every connection. The flag covers only this app's root container: the lifespan still opens and closes the containers of mounted apps that kept the default.

## API

| Symbol | Description |
|---|---|
| `setup_di(app, container, *, manage_lifespan=True)` | Registers the container on `app.state`, composes the lifespan (opens/closes the container unless `manage_lifespan=False`), 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 a sync or `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](https://pypi.org/project/modern-di-starlette)

## 📝 [License](https://github.com/modern-python/modern-di-starlette/blob/main/LICENSE)

## Part of `modern-python`

Built on [`modern-di`](https://github.com/modern-python/modern-di), a dependency-injection framework with an IoC container and scopes.

Browse the full list of templates and libraries in
[`modern-python`](https://github.com/modern-python); the org profile has the categorized index.
