Skip to content

FastAPI Extension

from sqlspec.extensions.fastapi import (
    DependencyDefaults,
    FieldNameType,
    FilterConfig,
    SQLSpecPlugin,
    SQLSpecTransactionMiddleware,
    provide_filters,
    set_request_tenant,
    tenant_bypass,
)

FastAPI lifespan plugin, request-scoped Depends() session/connection providers, deferred tenant receipt helpers, and declarative query-parameter filter dependency builders (SQLSpecSyncService and SQLSpecAsyncService are documented in Service Layer). See the FastAPI Integration Guide for usage examples.

Plugin & Middlewares

SQLSpecPlugin

Bases: SQLSpecPlugin

SQLSpec integration for FastAPI applications.

Extends Starlette integration with dependency injection helpers for FastAPI's Depends() system.

get_config

get_config(name=None)

Return a registered database configuration by identifier, or the sole configuration when omitted.

Parameters:

Name Type Description Default
name str | type[DatabaseConfigProtocol[Any, Any, Any]] | DatabaseConfigProtocol[Any, Any, Any] | None

Optional bind_key, session_key, connection_key, pool_key, unique config class, or config instance.

None

Returns:

Type Description
DatabaseConfigProtocol[Any, Any, Any]

Matching database configuration.

Raises:

Type Description
KeyError

No matching configuration exists, or name is ambiguous.

provide_session

provide_session(key=None)

Create dependency factory for session injection.

Returns an async callable compatible with FastAPI's Depends() that acquires deferred tenant leases on demand once an earlier dependency or middleware has called :func:~sqlspec.extensions.fastapi.set_request_tenant.

Parameters:

Name Type Description Default
key str | type[AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any] | SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]] | AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any] | SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any] | None

Optional session/bind key, unique config class, config instance, or None.

None

Returns:

Type Description
Callable[[Request], Awaitable[Any]]

Dependency callable for FastAPI Depends().

provide_async_session

provide_async_session(key=None)

Create dependency factory for async session injection.

Type-narrowed version of provide_session() returning AsyncDriverAdapterBase.

Parameters:

Name Type Description Default
key str | AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any] | type[AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]] | None

Optional session key, config class, or config instance.

None

Returns:

Type Description
Callable[[Request], Awaitable[AsyncDriverAdapterBase]]

Async dependency callable returning AsyncDriverAdapterBase.

provide_sync_session

provide_sync_session(key=None)

Create dependency factory for sync session injection.

Type-narrowed version of provide_session() returning SyncDriverAdapterBase.

Parameters:

Name Type Description Default
key str | SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any] | type[SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]] | None

Optional session key, config class, or config instance.

None

Returns:

Type Description
Callable[[Request], SyncDriverAdapterBase]

Dependency callable returning SyncDriverAdapterBase.

provide_connection

provide_connection(key=None)

Create dependency factory for connection injection.

Returns an async callable compatible with FastAPI's Depends() to inject a database connection into route handlers.

Parameters:

Name Type Description Default
key str | type[AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any] | SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]] | AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any] | SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any] | None

Optional session/bind key, unique config class, config instance, or None.

None

Returns:

Type Description
Callable[[Request], Awaitable[Any]]

Dependency callable for FastAPI Depends().

provide_async_connection

provide_async_connection(key=None)

Create dependency factory for async connection injection.

Parameters:

Name Type Description Default
key str | AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any] | type[AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]] | None

Optional session key, config class, or config instance.

None

Returns:

Type Description
Callable[[Request], Awaitable[Any]]

Async dependency callable returning the raw database connection.

provide_sync_connection

provide_sync_connection(key=None)

Create dependency factory for sync connection injection.

Parameters:

Name Type Description Default
key str | SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any] | type[SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]] | None

Optional session key, config class, or config instance.

None

Returns:

Type Description
Callable[[Request], Any]

Dependency callable returning the raw database connection.

get_session_async

get_session_async(request, key=None)

Get or create database session asynchronously, acquiring deferred tenant leases on demand.

Parameters:

Name Type Description Default
request Request

Starlette request instance.

required
key Any

Optional session key, bind key, config type, or config instance.

None

Returns:

Type Description
Any

Database session (driver instance).

get_connection_async

get_connection_async(request, key=None)

Get database connection asynchronously, acquiring deferred tenant leases on demand.

Parameters:

Name Type Description Default
request Request

Starlette request instance.

required
key Any

Optional session key, bind key, config type, or config instance.

None

Returns:

Type Description
Any

Database connection object.

provide_filters

provide_filters(config, dep_defaults=None)

Create filter dependency for FastAPI routes inheriting plugin cursor settings.

Dynamically generates a FastAPI dependency function that parses query parameters into SQLSpec filter objects. The returned callable can be used with FastAPI's Depends() for automatic filter injection.

Parameters:

Name Type Description Default
config FilterConfig

Filter configuration specifying which filters to enable.

required
dep_defaults DependencyDefaults | None

Optional dependency defaults for customization.

None

Returns:

Type Description
Callable[..., list[FilterTypes]]

Callable for use with Depends() that returns list of filters.

Shared Starlette Components

FastAPI reuses the Starlette request middleware and tenant helpers. They are documented once on the Starlette Extension page:

Filter Dependency Providers

provide_filters

provide_filters(config, dep_defaults=DEPENDENCY_DEFAULTS)

Create FastAPI dependency provider for filters based on configuration.

This function dynamically generates a FastAPI dependency function that parses query parameters into SQLSpec filter objects.

Parameters:

Name Type Description Default
config FilterConfig

Filter configuration specifying which filters to enable.

required
dep_defaults DependencyDefaults

Dependency defaults for filter configuration.

DEPENDENCY_DEFAULTS

Returns:

Type Description
Callable[..., list[FilterTypes]]

A FastAPI dependency callable that returns list of filters.

FilterConfig

Bases: TypedDict

Configuration for generated FastAPI filter dependencies.

All keys are optional. A filter dependency is created only for each enabled key. Field names are SQL-facing allowlist values; generated query parameter names and order-by aliases remain API-facing.

Attributes:

Name Type Description
id_filter NotRequired[type[UUID | int | str]]

Type of ID filter to enable. When set, creates an ids collection filter.

id_field NotRequired[str]

SQL-facing field name for ID filtering. Defaults to "id".

sort_field NotRequired[SortField]

Allowed SQL-facing field or fields for orderBy sorting.

sort_field_aliases NotRequired[dict[str, str]]

Additional API-facing orderBy aliases mapped to configured sort_field values.

sort_field_camelize NotRequired[bool]

Whether to accept camel-case aliases for configured sort fields. Defaults to True.

sort_order NotRequired[SortOrder]

Default sort order. Defaults to "desc".

pagination_type NotRequired[Literal['limit_offset', 'cursor']]

Pagination strategy to enable: "limit_offset" or "cursor".

pagination_cursor_keys NotRequired[CursorKeys]

Field names, (field, direction) pairs, or CursorKey values. The last key must be unique per row.

pagination_cursor_secret NotRequired[str | bytes]

Secret enabling HMAC-SHA256 signed cursors.

pagination_cursor_ttl NotRequired[int | float | timedelta]

Cursor expiration window in seconds or timedelta.

pagination_cursor_encrypted NotRequired[bool]

Encrypt cursor payloads at rest when a cursor secret is configured.

pagination_size NotRequired[int]

Default page size for limit/offset or cursor pagination.

pagination_max_size NotRequired[int]

Largest page size a client may request. Defaults to 1000.

search NotRequired[str | set[str] | list[str]]

SQL-facing field or fields to search. Strings may be comma-separated.

search_escape_wildcards NotRequired[bool]

Escape %, _, and the escape character in search input so they match literally. Defaults to True.

search_ignore_case NotRequired[bool]

Whether search filtering is case-insensitive. Defaults to False.

created_at NotRequired[bool]

Whether to enable created_at before/after range filtering.

updated_at NotRequired[bool]

Whether to enable updated_at before/after range filtering.

not_in_fields NotRequired[FieldNameType | set[FieldNameType] | list[str | FieldNameType]]

Field or fields that support NOT IN collection filtering.

in_fields NotRequired[FieldNameType | set[FieldNameType] | list[str | FieldNameType]]

Field or fields that support IN collection filtering.

null_fields NotRequired[str | set[str] | list[str]]

Field or fields that support IS NULL filtering.

not_null_fields NotRequired[str | set[str] | list[str]]

Field or fields that support IS NOT NULL filtering.

boolean_fields NotRequired[str | set[str] | list[str]]

Field or fields that support boolean filtering.

choice_fields NotRequired[ChoiceField | set[ChoiceField] | list[str | ChoiceField]]

Field or fields that support choices filtering.

DependencyDefaults

Default values for dependency generation.

CREATED_FILTER_DEPENDENCY_KEY

CREATED_FILTER_DEPENDENCY_KEY = 'created_filter'

ID_FILTER_DEPENDENCY_KEY

ID_FILTER_DEPENDENCY_KEY = 'id_filter'

LIMIT_OFFSET_FILTER_DEPENDENCY_KEY

LIMIT_OFFSET_FILTER_DEPENDENCY_KEY = 'limit_offset_filter'

UPDATED_FILTER_DEPENDENCY_KEY

UPDATED_FILTER_DEPENDENCY_KEY = 'updated_filter'

ORDER_BY_FILTER_DEPENDENCY_KEY

ORDER_BY_FILTER_DEPENDENCY_KEY = 'order_by_filter'

SEARCH_FILTER_DEPENDENCY_KEY

SEARCH_FILTER_DEPENDENCY_KEY = 'search_filter'

CURSOR_FILTER_DEPENDENCY_KEY

CURSOR_FILTER_DEPENDENCY_KEY = 'cursor_filter'

DEFAULT_PAGINATION_SIZE

DEFAULT_PAGINATION_SIZE = 20

DEFAULT_PAGINATION_MAX_SIZE

DEFAULT_PAGINATION_MAX_SIZE = 1000

FieldNameType

Bases: NamedTuple

Type for field name and associated type information for filter configuration.

name
name

Name of the field to filter on.

type_hint
type_hint = str

Type of the filter value. Defaults to str.