Configuration
Unlike django-rls (which reads a Django settings dict), FastAPI has no global
settings object, so configuration is an explicit RLSConfig value object. The
preferred path is to hand a config to the RLS facade; a process-wide active
config also exists for the low-level context API.
from fastapi_rls import RLSConfig, RLS
config = RLSConfig(require_context=True, default_roles="app_user")
rls = RLS(engine=engine, config=config)
Options
| Option | Default | Meaning |
|---|---|---|
require_context | False | Raise RLSContextRequiredError when a query helper runs with no identity set |
transaction_per_request | True | The session dependency wraps each request in a transaction and uses SET LOCAL |
reset_context_on_checkout | True | Install the pool-checkin scrub backstop on a sync engine |
audit_log | False | Emit structured INFO logs on context set/clear |
default_roles | "public" | Default TO clause for policies ("public" or a comma-separated identifier list) |
default_permissive | True | Policies are PERMISSIVE by default (vs RESTRICTIVE) |
key_prefix | "rls" | Session-variable namespace, e.g. rls.tenant_id |
registered_context_keys | () | Extra context keys (beyond user/tenant) that connection hygiene should scrub |
RLSConfig is a frozen dataclass. Derive variants with with_overrides:
prod = RLSConfig().with_overrides(require_context=True, default_roles="app_user")
Helper methods: full_key("tenant_id") → "rls.tenant_id";
all_context_keys() → every key hygiene clears.
The active (global) config
The low-level context API consults a process-wide active config. Set it with
configure:
from fastapi_rls import configure, RLSConfig, get_config
configure(RLSConfig(require_context=True)) # replace
configure(default_roles="app_user") # override fields of the current one
get_config() # read the active config
In an application, prefer passing an explicit config= to RLS(...) over
mutating the global — configure is a convenience for scripts and tests.
From environment variables
RLSConfig.from_env() builds a config from FASTAPI_RLS_-prefixed variables:
config = RLSConfig.from_env() # reads FASTAPI_RLS_* from the environment
| Variable | Maps to |
|---|---|
FASTAPI_RLS_REQUIRE_CONTEXT | require_context |
FASTAPI_RLS_AUDIT_LOG | audit_log |
FASTAPI_RLS_DEFAULT_ROLES | default_roles |
FASTAPI_RLS_DEFAULT_PERMISSIVE | default_permissive |
FASTAPI_RLS_KEY_PREFIX | key_prefix |
FASTAPI_RLS_REGISTERED_CONTEXT_KEYS | registered_context_keys (comma-separated) |
FASTAPI_RLS_RESET_CONTEXT_ON_CHECKOUT | reset_context_on_checkout |
FASTAPI_RLS_TRANSACTION_PER_REQUEST | transaction_per_request |
Booleans accept 1/true/yes/on (case-insensitive).
Validation
RLSConfig validates on construction: key_prefix must be a simple identifier,
and default_roles must be a non-empty string. Invalid values raise
ConfigurationError.