Skip to content

Middleware

TenancyMiddleware

Python
TenancyMiddleware(
    app: ASGIApp,
    manager: Any,
    excluded_paths: list[str] | None = None,
)

Raw ASGI middleware that resolves the current tenant per request.

Sets the tenant on TenantContext at the start of every HTTP request and restores the previous state at the end — even on error.

Parameters:

Name Type Description Default
app ASGIApp

The downstream ASGI application.

required
manager Any

The configured :class:~fastapi_tenancy.manager.TenancyManager.

required
excluded_paths list[str] | None

List of URL path prefixes that bypass tenancy resolution (e.g. ["/health", "/docs"]).

None

Example::

Text Only
from fastapi_tenancy.middleware.tenancy import TenancyMiddleware

app.add_middleware(
    TenancyMiddleware,
    manager=manager,
    excluded_paths=["/health", "/docs", "/openapi.json"],
)
Source code in src/fastapi_tenancy/middleware/tenancy.py
Python
def __init__(
    self,
    app: ASGIApp,
    manager: Any,  # TenancyManager — Any avoids circular import
    excluded_paths: list[str] | None = None,
) -> None:
    self._app = app
    self._manager = manager
    self._excluded: list[str] = excluded_paths or []