API reference
Everything below is importable from the top-level fastapi_rls package (the
integration classes are lazy-loaded, so importing the package never requires
SQLAlchemy or FastAPI to be installed).
Facade
RLS
The central handle that ties configuration, the registry, engines, dependencies, and reconciliation together. Build one per process.
RLS(
*,
engine=None, # sync Engine — dependencies, sync/audit, pool hygiene
async_engine=None, # AsyncEngine — async dependency
sessionmaker=None, # auto-created from engine if omitted
async_sessionmaker=None, # auto-created from async_engine if omitted
config=None, # RLSConfig; defaults to the active global config
registry=None, # PolicyRegistry; defaults to default_registry
install_hygiene=True, # install the pool-checkin scrub on a sync engine
)
| Method | Returns | Purpose |
|---|---|---|
session_dependency(*, identity, sessionmaker=None, is_local=None) | FastAPI dependency | Yields an RLS-scoped Session |
async_session_dependency(*, identity, sessionmaker=None, is_local=None) | FastAPI dependency | Yields an RLS-scoped AsyncSession |
sync(*, engine=None, drop_untracked=False, force=True) | SyncPlan | Apply the registry to the database |
plan(*, engine=None, drop_untracked=False, force=True) | SyncPlan | Compute the plan without applying |
audit(*, engine=None) | list[AuditFinding] | Report drift (read-only) |
Policies
| Class | Signature (key args) |
|---|---|
TenantPolicy | (name, *, column=None, tenant_field=None, context_key="tenant_id", context_type="integer", **base) |
UserPolicy | (name, *, column=None, user_field=None, context_key="user_id", context_type="integer", **base) |
CustomPolicy | (name, *, using, check=None, **base) |
BasePolicy | (name, *, table=None, operation="ALL", permissive=True, roles=None, key_prefix="rls") |
Common **base options come from BasePolicy: table, operation
(ALL/SELECT/INSERT/UPDATE/DELETE), permissive, roles, key_prefix.
context_type accepts integer/int/bigint/smallint/uuid/text/string.
Key methods: bind_table(table), require_table(), is_bound,
get_using_expression(), get_check_expression(). See
Policies.
Registry
PolicyRegistry
Holds bound policies grouped by table.
| Method | Purpose |
|---|---|
register(policy) | Add one policy (idempotent for the same object; raises on a name clash) |
register_many(policies) | Add several |
register_table(table, policies) | Bind and add |
tables() | Tables with policies |
policies_for(table) | Policies on a table |
all_policies() | Every registered policy |
clear() | Remove all |
default_registry is the module-level instance the mixin and CLI use by default.
Context
Executor-based helpers. Sync and async forms share the same bookkeeping.
| Sync | Async | Purpose |
|---|---|---|
set_rls_context(executor, key, value, *, system=False) | aset_rls_context | Set one key |
apply_rls_context(executor, mapping, *, system=False, is_local=True) | aapply_rls_context | Set a mapping |
clear_rls_context(executor) | aclear_rls_context | Clear context |
rls_context(executor, **keys) | arls_context | Scoped set/restore (context manager) |
system_rls_context(executor, **keys) | — | Scoped, auditable elevation |
require_rls_context() | — | Raise if no identity is present |
has_rls_identity_context() | — | Whether identity is set |
get_active_rls_context() | — | Read the in-process mirror (see caveat below) |
get_active_rls_context() is not reliable inside sync FastAPI route
handlers — read identity from your own dependency. See
request context.
Configuration
RLSConfig (frozen dataclass), configure(...), get_config(). See the
configuration reference.
Exceptions
All inherit from RLSError.
| Exception | Raised when |
|---|---|
RLSError | Base class |
PolicyError | Invalid policy construction (bad name/identifier, forbidden CustomPolicy SQL) |
ConfigurationError | Invalid config or a missing engine/sessionmaker |
RLSContextImmutableError | Overriding an already-set user_id/tenant_id without a system context |
RLSContextRequiredError | require_context=True and no identity is present |
TenantAccessDeniedError | A tenant access check fails |
Adapters and integrations
fastapi_rls.adapters.sqlalchemy—RLSMixin,SessionExecutor,AsyncSessionExecutor,collect_policies,install_pool_hygiene.fastapi_rls.middleware—RLSContextMiddleware,identity_from_state.fastapi_rls.alembic_ops— import to registerop.*directives.fastapi_rls.ddl— pure statement builders (enable_rls,create_policy, …).fastapi_rls.sync—plan_sync,apply_sync,audit,SyncPlan,AuditFinding.
Deferred to a later release
These are intentionally not in v0.1 and are documented so you know the boundary:
- SQLAlchemy-expression policies (the analog of django-rls'
Q-objectModelPolicy). - Hierarchical / recursive-CTE RLS.
- Context processors for injecting extra dynamic context variables.
- Native async pool-hygiene scrub (the async path relies on
SET LOCAL, which is sufficient on its own).