Multi-tenancy management module for FastAPI with tenant isolation and permission-aware middleware
Project description
tenants2fast-fastapi
🏢 Multi-tenancy management for FastAPI — tenant isolation, JWT-aware middleware, and permission-gated endpoints, all wired up in minutes.
Part of the *2fast-fastapi ecosystem: oauth2fast-fastapi → permissions2fast-fastapi → tenants2fast-fastapi.
Features
- 🔐 JWT-aware
TenantMiddleware— extracts user from Bearer token and sets tenant context automatically on every request - 🏗️ Isolated tenant databases — each tenant gets its own PostgreSQL database, created and initialized at runtime
- 🗂️
TenantandUserTenantSQLModel models — ready-to-use ORM models with audit timestamps - ⚡ Redis caching — tenant data and user permissions are cached via
permissions2fast-fastapi - 🔒
require_permissiondependency — guard any route with a single line using the RBAC system frompermissions2fast-fastapi
Installation
pip install tenants2fast-fastapi
Or with uv:
uv add tenants2fast-fastapi
Quick Start
from fastapi import Depends, FastAPI
from tenant2fast_fastapi import (
TenantMiddleware,
get_current_tenant,
get_current_user,
require_permission,
)
app = FastAPI()
# 1. Register the middleware
app.add_middleware(TenantMiddleware)
# 2. Use dependencies in your endpoints
@app.get("/me/tenant")
async def my_tenant(tenant=Depends(get_current_tenant)):
return {"name": tenant.name, "slug": tenant.slug}
@app.get("/reports", dependencies=[Depends(require_permission("/reports", "GET"))])
async def reports(user=Depends(get_current_user)):
return {"user": user.email}
See examples/basic_usage.py for a more complete example.
Configuration
All settings use the TENANT_ prefix and can be provided via environment variables or a .env file.
| Variable | Default | Description |
|---|---|---|
TENANT_DB_PREFIX |
tenant_ |
Prefix for per-tenant database names |
TENANT_SUPERUSER_DB__HOSTNAME |
localhost |
PG host for superuser operations |
TENANT_SUPERUSER_DB__PORT |
5432 |
PG port |
TENANT_SUPERUSER_DB__USERNAME |
postgres |
PG superuser username |
TENANT_SUPERUSER_DB__PASSWORD |
postgres |
PG superuser password |
TENANT_SUPERUSER_DB__NAME |
postgres |
Default DB for superuser connection |
TENANT_MAX_TENANT_CONNECTIONS |
5 |
Connection pool size per tenant |
In addition, all variables required by oauth2fast-fastapi (JWT, DB connections, mail) and permissions2fast-fastapi (Redis) must be set — see their respective READMEs.
Public API
from tenant2fast_fastapi import (
Tenant, # SQLModel ORM model (table: tenants)
UserTenant, # Many-to-many User ↔ Tenant (table: user_tenants)
TenantMiddleware, # Starlette BaseHTTPMiddleware
get_current_tenant, # FastAPI dependency → Tenant
get_current_user, # FastAPI dependency → User (from oauth2fast-fastapi)
require_permission, # Dependency factory → checks RBAC + cache
create_tenant_database, # async — creates a PG database for a tenant
get_tenant_engine, # returns (cached) AsyncEngine for a tenant DB
initialize_tenant_schema, # async — runs SQLModel.metadata.create_all on tenant DB
)
Development
# Clone and install in editable mode with dev + test dependencies
git clone https://github.com/AngelDanielSanchezCastillo/tenants2fast-fastapi
cd tenants2fast-fastapi
uv sync --group dev --group test
# Copy .env and adjust to your local setup
cp .env .env.local # or just edit .env directly
# Run tests (requires PostgreSQL + Redis)
uv run pytest tests/ -v
# Build distribution
uv build
Related Packages
License
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file tenants2fast_fastapi-0.3.1.tar.gz.
File metadata
- Download URL: tenants2fast_fastapi-0.3.1.tar.gz
- Upload date:
- Size: 37.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f705e5688c89505cd5eb1041be34a7ec07c3a1b3e4d68806f2e89114eaa75d17
|
|
| MD5 |
8e0aa1cc01760568464de41835059b00
|
|
| BLAKE2b-256 |
a625ffb15ff52911448fa13afc1ec0e130421f74e05d7dd7aa97abf42366237a
|
File details
Details for the file tenants2fast_fastapi-0.3.1-py3-none-any.whl.
File metadata
- Download URL: tenants2fast_fastapi-0.3.1-py3-none-any.whl
- Upload date:
- Size: 43.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
efd7562ff9fa389d81970c048c50054adbd5e2a83a3b153a52cd2d069383f353
|
|
| MD5 |
0528e31f273eaeda2e6af3af189d4dc9
|
|
| BLAKE2b-256 |
dab502fba29db021416c11950a6cc18da802453280d2ae229ceb3f61fe6652da
|