Skip to content

API reference

The following pages are autogenerated from the docstrings of the fastauth package.

fastauth

fastauth — a modular FastAPI authentication library.

FastAuthOptions

Bases: OptionsModel

Single Pydantic options object accepted by FastAuth.

FastAuth instance surfaces

auth.api

The trusted, in-process authentication API. Its methods call FastAuth's core flows directly and do not make HTTP requests.

user = await auth.api.create_user(
    email="admin@app.com",
    password="secure-password",
    name="Admin",
    metadata={"role": "admin"},
)

create_user() validates and hashes the password, runs database hooks, emits UserCreated, and returns a safe UserView. It does not create a session or refresh token and does not send verification email. Code with access to auth.api is trusted application code; add your own authorization before calling it with request-derived input.

get_user() reads a safe UserView by exactly one selector and returns None when no user matches:

user = await auth.api.get_user(by_email="admin@app.com")

auth.router

A standard, prefix-free FastAPI APIRouter. Include it explicitly when the application owns route placement:

app.include_router(auth.router, prefix="/api/auth", tags=["auth"])

This installs authentication routes only. It does not install FastAuth's exception handler, CSRF middleware, or security-headers middleware.

auth.add_middleware(app)

Installs the FastAuth exception handler, CSRF middleware, and security-headers middleware without including routes or selecting a prefix:

app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
auth.add_middleware(app)

Applications can omit add_middleware() only when they intentionally provide equivalent exception handling and application-wide security middleware. FastAuth.as_asgi() includes the router at options.app.base_path and installs this integration automatically.

auth.CurrentUser and auth.CurrentSession

Bound FastAPI Annotated dependencies for required authentication:

@app.get("/me")
async def me(user: auth.CurrentUser):
    return user


@app.get("/my-session")
async def my_session(session: auth.CurrentSession):
    return session

Anonymous requests receive FastAuth's canonical 401 response. CurrentUser resolves to UserView; CurrentSession resolves to SessionContext. With postponed annotations, auth must be a module-level binding so FastAPI can resolve the annotation. Factory- or closure-scoped instances can use Depends(auth.depends.user()) and Depends(auth.depends.session()) explicitly.

auth.on(EventType)

Registers a typed async event handler and returns the original function:

@auth.on(UserCreated)
async def send_welcome_email(event: UserCreated) -> None:
    await email_client.send(event.user_id, "Welcome!")

Matching events are delivered in registration order. Handler exceptions are logged and isolated so later handlers continue to run.

auth.hook(phase, target=...)

Registers an async database hook for an exact phase and target:

@auth.hook(HookPhase.BEFORE_CREATE, target="user")
async def prepare_user(context: HookContext) -> User:
    ...

Before-hook return values replace the payload passed to subsequent hooks. After-hook return values are ignored, and hook exceptions propagate to the calling mutation flow. Both decorator factories also support imperative registration, such as auth.on(UserCreated)(handler).

Configuration

fastauth.options

Public Pydantic options for the FastAuth runtime.

DynamicBaseUrlOptions

Bases: OptionsSection

Request-scoped base URL configuration.

FastAuthOptions

Bases: OptionsModel

Single Pydantic options object accepted by FastAuth.

MaintenanceOptions

Bases: OptionsSection

Bounds and retention policy for explicit maintenance runs.

OptionsModel

Bases: BaseModel

Common base for user-facing option sections.

OptionsSection

Bases: OptionsModel

Common base for grouped user-facing options.

ProductionSafetyOptions

Bases: OptionsSection

Independently configurable safety policies for production deployments.

parse_duration(value)

Normalize common duration inputs to timedelta for Pydantic fields.

Adapters

fastauth.storage.base

Storage adapter protocols and reusable base class.

BaseDatabaseAdapter

Reusable adapter base with explicit unsupported-feature defaults.

Subclass this when implementing a backend. Override the core auth methods here, then add optional store protocol methods only for the plugins or database-backed features your adapter supports.

CoreAuthAdapter

Bases: UserStore, SessionStore, RefreshTokenStore, AccountStore, VerificationStore, Protocol

Minimum storage surface used by fastauth's built-in auth flows.

DatabaseAdapter

Bases: CoreAuthAdapter, MaintenanceStore, Protocol

Core storage adapter required by fastauth's built-in auth flows.

Plugin and optional infrastructure storage is expressed through separate protocols: ApiKeyStore, JwksKeyStore, AuditLogStore, and RateLimitStore. Implement only the capabilities your configuration enables.

Plugins

fastauth.plugins.base

Plugin abstract base and the PluginRegistry.

Capability

Bases: WireModel

A runtime feature enabled by core configuration or an installed plugin.

EndpointHookSpec

Bases: PluginContractModel

Before/after endpoint hook contributed by a plugin.

EndpointInfo

Bases: BaseModel

Serializable public metadata for a registered HTTP endpoint.

EndpointSpec

Bases: BaseModel

Describes a plugin-provided HTTP endpoint.

Plugin

Bases: ABC

Subclass to add features. Override only the hooks you need.

PluginApiNamespace

Bases: BaseModel

A plugin-contributed public server API namespace.

PluginApiRegistry

Lookup surface for plugin-contributed server API namespaces.

PluginContractModel

Bases: BaseModel

Common immutable base for plugin extension contract DTOs.

PluginErrorCode

Bases: PluginContractModel

Error code contributed by a plugin.

PluginInfo

Bases: BaseModel

Public metadata describing a plugin's runtime contribution.

PluginMiddlewareSpec

Bases: PluginContractModel

Route-scoped middleware contributed by a plugin.

PluginOptions

Bases: BaseModel

Common immutable base for first-party plugin configuration.

PluginRegistry

Validates and aggregates a list of Plugin instances.

RateLimitRule

Bases: BaseModel

Declarative rate-limit rule for a plugin endpoint.

RequestHookSpec

Bases: PluginContractModel

Request interceptor contributed by a plugin.

ResponseHookSpec

Bases: PluginContractModel

Response interceptor contributed by a plugin.