Skip to main content

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
)
MethodReturnsPurpose
session_dependency(*, identity, sessionmaker=None, is_local=None)FastAPI dependencyYields an RLS-scoped Session
async_session_dependency(*, identity, sessionmaker=None, is_local=None)FastAPI dependencyYields an RLS-scoped AsyncSession
sync(*, engine=None, drop_untracked=False, force=True)SyncPlanApply the registry to the database
plan(*, engine=None, drop_untracked=False, force=True)SyncPlanCompute the plan without applying
audit(*, engine=None)list[AuditFinding]Report drift (read-only)

Policies

ClassSignature (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.

MethodPurpose
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.

SyncAsyncPurpose
set_rls_context(executor, key, value, *, system=False)aset_rls_contextSet one key
apply_rls_context(executor, mapping, *, system=False, is_local=True)aapply_rls_contextSet a mapping
clear_rls_context(executor)aclear_rls_contextClear context
rls_context(executor, **keys)arls_contextScoped 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)
warning

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.

ExceptionRaised when
RLSErrorBase class
PolicyErrorInvalid policy construction (bad name/identifier, forbidden CustomPolicy SQL)
ConfigurationErrorInvalid config or a missing engine/sessionmaker
RLSContextImmutableErrorOverriding an already-set user_id/tenant_id without a system context
RLSContextRequiredErrorrequire_context=True and no identity is present
TenantAccessDeniedErrorA tenant access check fails

Adapters and integrations

  • fastapi_rls.adapters.sqlalchemyRLSMixin, SessionExecutor, AsyncSessionExecutor, collect_policies, install_pool_hygiene.
  • fastapi_rls.middlewareRLSContextMiddleware, identity_from_state.
  • fastapi_rls.alembic_ops — import to register op.* directives.
  • fastapi_rls.ddl — pure statement builders (enable_rls, create_policy, …).
  • fastapi_rls.syncplan_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-object ModelPolicy).
  • 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).