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-fastapi → permissions2fast-fastapi → tenants2fast-fastapi.

📖 Conventions reference: this package follows the 2fast-handbook for ecosystem conventions (structure, versioning, README, commits, release).


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
TENANT_REDIS_URL unset Optional Redis URL for tenant caches
TENANT_REDIS_TTL 300 Tenant cache TTL in seconds
TENANT_SEED_PROFILE dev Seeder profile (dev/prod)

In addition, all variables required by oauth2fast-fastapi (JWT, refresh tokens, DB connections, mail) and permissions2fast-fastapi (Redis) must be set — see their respective READMEs.

Auth error contract

get_current_tenant / get_current_user (and the tenant RBAC dependencies) distinguish authentication from authorization:

Situation Status error.type WWW-Authenticate
No token 401 TokenMissing Bearer
Expired token 401 TokenExpired Bearer error="expired_token"
Malformed / bad signature 401 TokenInvalid Bearer error="invalid_token"
Valid token, no tenant 403 TenantRequired —
Inactive tenant 403 TenantInactive —
User not in tenant DB 403 TenantUserMissing —
Missing tenant permission 403 PermissionDenied —
Missing tenant role 403 RoleMissing —

Install the envelope handler once at startup:

from tools2fast_fastapi import install_auth_error_handler
install_auth_error_handler(app)

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

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

UUID migration coordination (0.10.1+)

tenant_users.user_id is backfilled from the _uuid_migration_user_map table left by oauth2fast-fastapi >= 0.8.2 (requires permissions2fast-fastapi >= 0.12.2). This chain is the last AUTH-lane consumer and drops the map. Upgrade the lane in order: oauth -> permissions -> tenant2fast-auth.

Metadata

Release files for tenants2fast-fastapi 0.10.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tenants2fast-fastapi 0.10.1
File Size Uploaded Provenance Actions
tenants2fast_fastapi-0.10.1.tar.gz 85.2 kB Without provenance Details for tenants2fast_fastapi-0.10.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tenants2fast-fastapi 0.10.1
File Interpreter ABI Platform Actions
tenants2fast_fastapi-0.10.1-py3-none-any.whl Python 3 none any Details for tenants2fast_fastapi-0.10.1-py3-none-any.whl

Total release size: 159.9 kB

Release files / tenants2fast_fastapi-0.10.1.tar.gz

Download URL tenants2fast_fastapi-0.10.1.tar.gz
Size 85.2 kB
Tags Source
SHA-256 checksum
How to use checksums
59de17d1a3c4ced396d9f4577ef003b92a66f21887392d54d25900881973fe1f
BLAKE2b-256 checksum
How to use checksums
2d9b010341395c38188b93e3de8fed31cbdef8e3a473488cea9ffb7471e85775
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.10

Release files / tenants2fast_fastapi-0.10.1-py3-none-any.whl

Download URL tenants2fast_fastapi-0.10.1-py3-none-any.whl
Size 74.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0ad78f2848090e704b78f75ce73dd0706b3dc0d42b3a2be686325aab2999e24c
BLAKE2b-256 checksum
How to use checksums
b616ee0d1b918eee9354cfcaab275e73789094f5295fc431291b2620767c5cfa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.10

Security for tenants2fast-fastapi 0.10.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.10.1 This release

2 release files No provenance

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