Skip to main content

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-fastapipermissions2fast-fastapitenants2fast-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
  • 🗂️ Tenant and TenantUser SQLModel models — ready-to-use ORM models with audit timestamps
  • Redis caching — tenant data and user permissions are cached via permissions2fast-fastapi
  • 🔒 require_permission dependency — guard any route with a single line using the RBAC system from permissions2fast-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)
    TenantUser,               # Many-to-many User ↔ Tenant (table: tenant_users)
    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

Package PyPI Purpose
log2fast-fastapi PyPI Structured logging
pgsqlasync2fast-fastapi PyPI Async PostgreSQL connection manager
mailing2fast-fastapi PyPI SMTP email sender
oauth2fast-fastapi PyPI JWT Auth + User management
permissions2fast-fastapi PyPI RBAC + Redis permission cache

📋 Naming Conventions

This package follows consistent naming conventions for models and database tables:

Model Classes (Python)

  • Singular PascalCase
  • Examples: User, Role, Permission, Category, Route

Database Tables

  • Plural snake_case
  • Examples: users, roles, permissions, categories, routes

Many-to-Many Join Tables

  • Plural snake_case on both table names
  • Alphabetical order of the two table names
  • Examples: role_users (r < u), permission_roles (p < r), permission_routes (p < r)

Tenant-Local vs Auth DB Models

  • Auth DB: Tenant (table: tenants), TenantUser (table: tenant_users) - maps users ↔ tenants
  • Tenant DB: User, Role, Permission, Category, Route - local tenant entities

Generic Categories

  • Use Category for generic categorization (not PermissionCategory)
  • Can be reused across different entity types

License

MIT © Angel Daniel Sanchez Castillo

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tenants2fast_fastapi-0.6.1.tar.gz (45.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tenants2fast_fastapi-0.6.1-py3-none-any.whl (51.0 kB view details)

Uploaded Python 3

File details

Details for the file tenants2fast_fastapi-0.6.1.tar.gz.

File metadata

  • Download URL: tenants2fast_fastapi-0.6.1.tar.gz
  • Upload date:
  • Size: 45.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.13.9

File hashes

Hashes for tenants2fast_fastapi-0.6.1.tar.gz
Algorithm Hash digest
SHA256 03a1f6fe85ef5e16cf90337635fb7ecfda163fbf3d5d617b955ecef912bc53c9
MD5 c7b7026a1d8db7d693dfcde9cd10316d
BLAKE2b-256 03c1f262690c6c88725a71cbfe123e6132154955044dfaf09a4c7e37535e35bf

See more details on using hashes here.

File details

Details for the file tenants2fast_fastapi-0.6.1-py3-none-any.whl.

File metadata

File hashes

Hashes for tenants2fast_fastapi-0.6.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9db5ee3f45469d395826ed94f4dc26e20e7fa41e86cb731fe4577eb158edcdb0
MD5 651368366f8ed0860e1e64526b51066e
BLAKE2b-256 73453ed4f6cbafb3a9ed8f1c536db5601e3e6aef65b0d765d693a3027dd023c1

See more details on using hashes here.

Release history Release notifications | RSS feed

0.6.3

2 files

0.6.2

2 files

This release

0.6.1 This release

2 files

0.6.0

2 files

0.5.1

2 files

0.5.0

2 files

0.4.1

2 files

0.4.0

2 files

0.3.2

2 files

0.3.1

2 files

0.3.0

2 files

0.2.7

2 files

0.2.6

2 files

0.2.5

2 files

0.2.4

2 files

0.2.3

2 files

0.2.2

2 files

0.2.1

2 files

0.2.0

2 files

0.1.1

2 files

0.1.0

2 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