Skip to main content

FastAPI RLS

PostgreSQL Row Level Security for FastAPI & SQLAlchemy

fastapi-rls is an open-source Python library that brings PostgreSQL Row Level Security to FastAPI and SQLAlchemy applications. It enforces multi-tenant and per-user data isolation at the database level, where it cannot be bypassed by a forgotten WHERE clause. The FastAPI/SQLAlchemy sibling of django-rls.

PyPI versionSupported Python versionsCI statusBSD-3-Clause license

pip install "fastapi-rls[fastapi]"
app.py
from fastapi import Depends, FastAPI
from sqlalchemy import select
from sqlalchemy.orm import Session
from fastapi_rls import RLS

rls = RLS(engine=engine)

def identity(user=Depends(get_current_user)) -> dict:
return {"tenant_id": user.tenant_id}

get_session = rls.session_dependency(identity=identity)
app = FastAPI()

@app.get("/documents")
def list_documents(session: Session = Depends(get_session)):
# PostgreSQL filters by tenant — no WHERE clause required.
return session.scalars(select(Document)).all()

Why fastapi-rls

Enforced by PostgreSQL

Policies compile to native ROW LEVEL SECURITY. Isolation is enforced by the database on every SELECT/INSERT/UPDATE/DELETE — not by application code you have to remember to write.

ORM-agnostic core

Policies, context, and DDL have zero framework dependencies. SQLAlchemy, FastAPI, and Alembic are optional adapters. The security-critical code is small, auditable, and testable without a database.

Leak-proof by construction

Identity is applied with SET LOCAL inside a per-request transaction and scrubbed on pool checkout. A request with no context sees no rows — never everyone’s.

Sync and async

First-class support for both Session and AsyncSession. Copy-on-write context vars keep concurrent requests isolated across asyncio tasks and threadpool threads.

Immutable identity

user_id and tenant_id cannot be silently overridden mid-request. Elevating requires an explicit, auditable system context.

Migrate your way

Alembic operation directives (op.create_policy) for migration users, and a standalone fastapi-rls CLI (sync/plan/audit) for everyone else.