Sure! Below is a Python-based Tenant Routing Service. This is a simplified example suitable for development or internal use that demonstrates how to route incoming requests to different tenants based on a request header (e.g., X-Tenant-ID). We'll build this using FastAPI for the web framework and demonstrate basic routing, tenant identification, and mock tenant-specific logic.
🚀 Features:
- Accepts HTTP requests with a custom header (X-Tenant-ID).
- Routes the request internally based on the tenant.
- Supports mock tenant-specific handlers.
- Logs the tenant being served for each request.
📦 Requirements
Install these packages first:
pip install fastapi uvicorn
🧠 Project Structure
tenant_router/
│
├── main.py # Entry point for FastAPI app
├── router.py # Tenant routing logic
└── tenants/ # Tenant-specific handlers/modules
├── __init__.py
├── tenant_a.py
└── tenant_b.py
📁 tenants/tenant_a.py
def handle_request():
return {"tenant": "Tenant A", "message": "Hello from Tenant A!"}
📁 tenants/tenant_b.py
def handle_request():
return {"tenant": "Tenant B", "message": "Greetings from Tenant B!"}
📁 router.py
from importlib import import_module
from fastapi import HTTPException
TENANT_MODULE_MAP = {
"tenant-a": "tenants.tenant_a",
"tenant-b": "tenants.tenant_b"
}
def get_tenant_handler(tenant_id: str):
module_path = TENANT_MODULE_MAP.get(tenant_id.lower())
if not module_path:
raise HTTPException(status_code=404, detail=f"Tenant {tenant_id} not found")
try:
module = import_module(module_path)
return module.handle_request
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error loading tenant handler: {str(e)}")
📁 main.py
from fastapi import FastAPI, Header, HTTPException
from router import get_tenant_handler
app = FastAPI(title="Tenant Routing Service")
@app.get("/api/data")
async def get_data(x_tenant_id: str = Header(..., description="Tenant Identifier")):
try:
handler = get_tenant_handler(x_tenant_id)
response = handler()
return response
except HTTPException as he:
raise he
except Exception as e:
raise HTTPException(status_code=500, detail=f"Unexpected error: {str(e)}")
▶️ Running the Server
uvicorn main:app --reload
🧪 Test the Service
Use curl or Postman:
curl -H "X-Tenant-ID: tenant-a" http://localhost:8000/api/data
curl -H "X-Tenant-ID: tenant-b" http://localhost:8000/api/data
curl -H "X-Tenant-ID: unknown" http://localhost:8000/api/data
✅ Sample Output
For tenant-a:
{
"tenant": "Tenant A",
"message": "Hello from Tenant A!"
}
🔐 Notes & Extensions
This is a minimal viable example. In production, you'd want to:
- Validate tenant IDs against a database or config.
- Support subdomains or path-based routing (e.g., /tenant-a/api/data).
- Add middleware for consistent tenant extraction/logging/auth.
- Use dependency injection for cleaner architecture.
- Implement isolation between tenants (e.g., separate DB schemas or Redis instances).
Would you like me to extend this to support dynamic tenant loading, database-backed configuration, or subdomain-based routing?