<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://johnwick.cc/index.php?action=history&amp;feed=atom&amp;title=Multi-Tenancy_in_FastAPI%3A_A_Complete_Guide</id>
	<title>Multi-Tenancy in FastAPI: A Complete Guide - Revision history</title>
	<link rel="self" type="application/atom+xml" href="https://johnwick.cc/index.php?action=history&amp;feed=atom&amp;title=Multi-Tenancy_in_FastAPI%3A_A_Complete_Guide"/>
	<link rel="alternate" type="text/html" href="https://johnwick.cc/index.php?title=Multi-Tenancy_in_FastAPI:_A_Complete_Guide&amp;action=history"/>
	<updated>2026-05-07T08:26:41Z</updated>
	<subtitle>Revision history for this page on the wiki</subtitle>
	<generator>MediaWiki 1.44.1</generator>
	<entry>
		<id>https://johnwick.cc/index.php?title=Multi-Tenancy_in_FastAPI:_A_Complete_Guide&amp;diff=3157&amp;oldid=prev</id>
		<title>PC: Created page with &quot;Building modern SaaS applications often requires serving multiple customers (tenants) from the same application while keeping their data securely isolated. This concept is called multi-tenancy. In this article, we will dive deep into multi-tenancy in FastAPI, explore different approaches, and implement a practical example to understand it better.    What is Multi-Tenancy? Multi-tenancy is an architectural pattern where a single application serves multiple customers (te...&quot;</title>
		<link rel="alternate" type="text/html" href="https://johnwick.cc/index.php?title=Multi-Tenancy_in_FastAPI:_A_Complete_Guide&amp;diff=3157&amp;oldid=prev"/>
		<updated>2025-12-13T22:33:09Z</updated>

		<summary type="html">&lt;p&gt;Created page with &amp;quot;Building modern SaaS applications often requires serving multiple customers (tenants) from the same application while keeping their data securely isolated. This concept is called multi-tenancy. In this article, we will dive deep into multi-tenancy in FastAPI, explore different approaches, and implement a practical example to understand it better.    What is Multi-Tenancy? Multi-tenancy is an architectural pattern where a single application serves multiple customers (te...&amp;quot;&lt;/p&gt;
&lt;p&gt;&lt;b&gt;New page&lt;/b&gt;&lt;/p&gt;&lt;div&gt;Building modern SaaS applications often requires serving multiple customers (tenants) from the same application while keeping their data securely isolated. This concept is called multi-tenancy.&lt;br /&gt;
In this article, we will dive deep into multi-tenancy in FastAPI, explore different approaches, and implement a practical example to understand it better.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
What is Multi-Tenancy?&lt;br /&gt;
Multi-tenancy is an architectural pattern where a single application serves multiple customers (tenants). Each tenant might represent a company, department, or user group.&lt;br /&gt;
&lt;br /&gt;
There are two main approaches to multi-tenancy:&lt;br /&gt;
* 		Database-per-tenant&lt;br /&gt;
* 		Each tenant has a completely separate database.&lt;br /&gt;
* 		Provides strong isolation.&lt;br /&gt;
* 		Harder to scale when the number of tenants grows.&lt;br /&gt;
2. Shared-database with tenant separation&lt;br /&gt;
* 		All tenants share the same database, but data is separated using a tenant_id column.&lt;br /&gt;
* 		Easier to scale and maintain.&lt;br /&gt;
* 		Requires strict application-level enforcement of data isolation.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Why Use Multi-Tenancy in FastAPI?&lt;br /&gt;
* 		Scalability: One codebase can handle multiple customers.&lt;br /&gt;
* 		Cost efficiency: Shared infrastructure reduces hosting costs.&lt;br /&gt;
* 		Maintainability: Deploy, monitor, and upgrade only one application instead of multiple.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Implementing Multi-Tenancy in FastAPI&lt;br /&gt;
Let’s build an example where we implement a shared-database multi-tenancy approach in FastAPI using SQLAlchemy.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Step 1: Project Setup&lt;br /&gt;
Install required dependencies:&lt;br /&gt;
&lt;br /&gt;
pip install fastapi uvicorn sqlalchemy psycopg2-binary&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Step 2: Database Model with Tenant Separation&lt;br /&gt;
We’ll create a users table where each user is linked to a tenant via tenant_id.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
from sqlalchemy import Column, Integer, String, ForeignKey&lt;br /&gt;
from sqlalchemy.orm import declarative_base, relationship&lt;br /&gt;
&lt;br /&gt;
Base = declarative_base()&lt;br /&gt;
&lt;br /&gt;
class Tenant(Base):&lt;br /&gt;
    __tablename__ = &amp;quot;tenants&amp;quot;&lt;br /&gt;
    id = Column(Integer, primary_key=True, index=True)&lt;br /&gt;
    name = Column(String, unique=True)&lt;br /&gt;
    users = relationship(&amp;quot;User&amp;quot;, back_populates=&amp;quot;tenant&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
class User(Base):&lt;br /&gt;
    __tablename__ = &amp;quot;users&amp;quot;&lt;br /&gt;
    id = Column(Integer, primary_key=True, index=True)&lt;br /&gt;
    name = Column(String)&lt;br /&gt;
    tenant_id = Column(Integer, ForeignKey(&amp;quot;tenants.id&amp;quot;))&lt;br /&gt;
    tenant = relationship(&amp;quot;Tenant&amp;quot;, back_populates=&amp;quot;users&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here:&lt;br /&gt;
* 		Tenant table stores tenant information.&lt;br /&gt;
* 		User table is linked to tenants through tenant_id.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Step 3: Middleware for Tenant Identification&lt;br /&gt;
We need to identify which tenant is making a request. One common approach is to use a custom header (X-Tenant-ID).&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
from fastapi import FastAPI, Request, HTTPException&lt;br /&gt;
&lt;br /&gt;
app = FastAPI()&lt;br /&gt;
&lt;br /&gt;
@app.middleware(&amp;quot;http&amp;quot;)&lt;br /&gt;
async def tenant_middleware(request: Request, call_next):&lt;br /&gt;
    tenant_id = request.headers.get(&amp;quot;X-Tenant-ID&amp;quot;)&lt;br /&gt;
    if not tenant_id:&lt;br /&gt;
        raise HTTPException(status_code=400, detail=&amp;quot;X-Tenant-ID header missing&amp;quot;)&lt;br /&gt;
    &lt;br /&gt;
    request.state.tenant_id = tenant_id&lt;br /&gt;
    response = await call_next(request)&lt;br /&gt;
    return response&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This middleware ensures that every request includes a tenant ID.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Step 4: Dependency for Tenant-Aware Queries&lt;br /&gt;
We’ll use request.state.tenant_id to filter tenant-specific data.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
from fastapi import Depends&lt;br /&gt;
&lt;br /&gt;
def get_tenant_id(request: Request):&lt;br /&gt;
    return request.state.tenant_id&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Step 5: Tenant-Specific Endpoints&lt;br /&gt;
Now, let’s implement endpoints to create and fetch users for a specific tenant.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
from fastapi import Depends&lt;br /&gt;
from sqlalchemy.orm import Session&lt;br /&gt;
from database import get_db  # assume we have a DB session dependency&lt;br /&gt;
from models import User&lt;br /&gt;
&lt;br /&gt;
@app.post(&amp;quot;/users/&amp;quot;)&lt;br /&gt;
def create_user(name: str, db: Session = Depends(get_db), tenant_id: str = Depends(get_tenant_id)):&lt;br /&gt;
    user = User(name=name, tenant_id=tenant_id)&lt;br /&gt;
    db.add(user)&lt;br /&gt;
    db.commit()&lt;br /&gt;
    db.refresh(user)&lt;br /&gt;
    return user&lt;br /&gt;
&lt;br /&gt;
@app.get(&amp;quot;/users/&amp;quot;)&lt;br /&gt;
def list_users(db: Session = Depends(get_db), tenant_id: str = Depends(get_tenant_id)):&lt;br /&gt;
    users = db.query(User).filter(User.tenant_id == tenant_id).all()&lt;br /&gt;
    return users&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here:&lt;br /&gt;
* 		create_user ensures that new users are always linked to the current tenant.&lt;br /&gt;
* 		list_users ensures that only tenant-specific users are retrieved.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Step 6: Testing the Multi-Tenancy&lt;br /&gt;
&lt;br /&gt;
Create a Tenant&lt;br /&gt;
&lt;br /&gt;
INSERT INTO tenants (name) VALUES (&amp;#039;Tenant A&amp;#039;), (&amp;#039;Tenant B&amp;#039;);&lt;br /&gt;
&lt;br /&gt;
Add Users for Tenant A&lt;br /&gt;
&lt;br /&gt;
curl -X POST &amp;quot;http://localhost:8000/users/&amp;quot; -H &amp;quot;X-Tenant-ID: 1&amp;quot; -d &amp;quot;name=Alice&amp;quot;&lt;br /&gt;
curl -X POST &amp;quot;http://localhost:8000/users/&amp;quot; -H &amp;quot;X-Tenant-ID: 1&amp;quot; -d &amp;quot;name=Bob&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Add Users for Tenant B&lt;br /&gt;
&lt;br /&gt;
curl -X POST &amp;quot;http://localhost:8000/users/&amp;quot; -H &amp;quot;X-Tenant-ID: 2&amp;quot; -d &amp;quot;name=Charlie&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Fetch Users for Tenant A&lt;br /&gt;
&lt;br /&gt;
curl -X GET &amp;quot;http://localhost:8000/users/&amp;quot; -H &amp;quot;X-Tenant-ID: 1&amp;quot;&lt;br /&gt;
# Returns: Alice, Bob&lt;br /&gt;
&lt;br /&gt;
Fetch Users for Tenant B&lt;br /&gt;
&lt;br /&gt;
curl -X GET &amp;quot;http://localhost:8000/users/&amp;quot; -H &amp;quot;X-Tenant-ID: 2&amp;quot;&lt;br /&gt;
# Returns: Charlie&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Best Practices for Multi-Tenancy in FastAPI&lt;br /&gt;
* 		Always enforce tenant filtering in every database query.&lt;br /&gt;
* 		Use middleware to extract tenant identifiers from headers or subdomains.&lt;br /&gt;
* 		Consider database-per-tenant if you need strict data isolation.&lt;br /&gt;
* 		Secure tenant identification — don’t allow clients to manipulate tenant IDs directly; use authentication tokens linked to tenants.&lt;br /&gt;
* 		Scalability — monitor database size and query performance as tenants increase.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Conclusion&lt;br /&gt;
Multi-tenancy is a powerful design pattern for SaaS applications. In this blog, we explored how to implement tenant-aware APIs in FastAPI using a shared-database approach. By enforcing tenant separation at the middleware and query level, we can efficiently serve multiple tenants while maintaining data security.&lt;br /&gt;
For large-scale SaaS applications, carefully evaluate between database-per-tenant and shared-database multi-tenancy based on your isolation, cost, and scalability requirements.&lt;br /&gt;
&lt;br /&gt;
Read the full article here: https://medium.com/@rameshkannanyt0078/multi-tenancy-in-fastapi-a-complete-guide-e6923702490a&lt;/div&gt;</summary>
		<author><name>PC</name></author>
	</entry>
</feed>