Ir para o conteúdo

tempest_fastapi_sdk.settings

BaseAppSettings, os mixins de settings compostos e as credenciais tipadas.

« Admin, dados e API


BaseAppSettings

Bases: BaseSettings

Shared configuration for Settings classes across projects.

Provides the canonical pydantic-settings config block; concrete projects subclass this and add their domain-specific fields (database URLs, secrets, third-party keys, etc.).

Every SDK settings mixin (DatabaseSettings, RedisSettings, …) subclasses this class, so a composed Settings must list BaseAppSettings last::

class Settings(DatabaseSettings, RedisSettings, BaseAppSettings):
    ...

Listing it earlier is an invalid MRO and fails at class creation with the actionable message raised by :class:AppSettingsMeta.

The defaults:

  • env_file=".env" — load environment variables from a local .env file when present.
  • extra="ignore" — silently drop unexpected env vars instead of raising at startup.
  • case_sensitive=True — env var names are matched exactly.
  • frozen=True — settings are immutable after construction.
  • str_strip_whitespace=True — trim accidental whitespace around env values.
  • from_attributes=True — allow building from objects with attribute access (rarely needed for settings, but harmless).
  • hide_input_in_errors=True — a validation error never echoes the input. On a BaseSettings the input of a model-level error is the whole merged environment: without this flag a missing required field prints input_value={'JWT_SECRET': ...} into the boot traceback and the container log, and a malformed value (a URL carrying a password) is echoed as is. Override it in your own model_config to get the input back.

Four extension points live here because every mixin and service needs them:

  • :meth:production_violations — the cooperative hook :class:~tempest_fastapi_sdk.settings.EnvironmentSettings calls when ENV=production. Each mixin overrides it, calls super() and appends the development values it owns.
  • :meth:disabled_integrations — the same cooperative shape, for the integrations a <NAME>_ENABLED flag switched off.
  • :attr:DEPRECATED_ENV_ALIASES — 1:1 old-to-new environment variable renames collected across the MRO. :class:DeprecatedEnvAliasesSettingsSource reads the old name from both the process environment and .env without requiring AliasChoices on each field, refuses clashes when old and new differ, and emits a DeprecationWarning plus a structured boot log when the old name populates the field.
  • :attr:DEPRECATED_ENV_CONVERTERS — canonical name to converter function (Mapping[str, str]) -> str | None for non-1:1 migrations (unit changes such as days to seconds, or splitting / composing variables such as REDIS_HOST/REDIS_PORT into REDIS_URL). Collected across the MRO with the same conflict check, warning, boot log and ENV_ALIASES_STRICT enforcement.

Attributes:

Name Type Description
model_config SettingsConfigDict

The pydantic-settings configuration.

DEPRECATED_ENV_ALIASES ClassVar[Mapping[str, str]]

Old environment variable name mapped to the canonical name that replaced it. Declared per class and collected across the whole MRO, so a subclass adds entries without repeating the parent's.

DEPRECATED_ENV_CONVERTERS ClassVar[Mapping[str, EnvAliasConverter]]

Canonical environment variable name mapped to a converter function receiving the merged raw environment mapping and returning the converted string value or None. Declared per class and collected across the whole MRO.

settings_customise_sources classmethod

settings_customise_sources(
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]

Keep pydantic-settings' default sources plus deprecated env resolution.

The source order is pydantic-settings' own (init kwargs, process environment, .env file), followed by :class:DeprecatedEnvAliasesSettingsSource (which validates conflicts, enforces ENV_ALIASES_STRICT, and supplies any canonical field not already set from DEPRECATED_ENV_ALIASES or DEPRECATED_ENV_CONVERTERS), followed by the secrets directory.

A Settings class that overrides this hook itself replaces the resolution; include DeprecatedEnvAliasesSettingsSource(settings_cls, (env_settings, dotenv_settings)) in the returned tuple (or call super().settings_customise_sources(...)) to keep it.

Parameters:

Name Type Description Default
settings_cls type[BaseSettings]

The class being built.

required
init_settings PydanticBaseSettingsSource

Keyword arguments passed to the constructor.

required
env_settings PydanticBaseSettingsSource

The process environment.

required
dotenv_settings PydanticBaseSettingsSource

The .env file.

required
file_secret_settings PydanticBaseSettingsSource

The secrets directory.

required

Returns:

Type Description
PydanticBaseSettingsSource

tuple[PydanticBaseSettingsSource, ...]: The sources in

...

priority order, including deprecated alias resolution.

Raises:

Type Description
SettingsError

When a deprecated environment variable or converter conflicts with its canonical replacement, or when ENV_ALIASES_STRICT is truthy and any deprecated variable or converter matched.

production_violations

production_violations() -> list[str]

List the development-only values this settings object holds.

:class:~tempest_fastapi_sdk.settings.EnvironmentSettings calls this when ENV=production and refuses to build when the list is not empty. The base implementation contributes nothing; each SDK mixin overrides it cooperatively — call super() first, then append — so a composed Settings collects the checks of every mixin it lists. A service adds its own rule the same way, and can drop one it has deliberately accepted by filtering the list super() returns.

Every entry names the field and the reason, never the value: the list ends up in a boot error, and the value is often a secret.

Returns:

Type Description
list[str]

list[str]: One "FIELD: reason" entry per violation.

disabled_integrations

disabled_integrations() -> list[str]

List the integrations this settings object switched off.

The companion of :meth:production_violations for deployments that ship in phases. A mixin modelling a third-party integration (StorageSettings, EmailSettings, FirebaseSettings, RevenueCatSettings, ZapSettings) declares a <NAME>_ENABLED flag; with it off, the mixin's production checks are skipped and its name is appended here, so the switch is never invisible: log the list at boot, or show it in a readiness detail.

Composed the same way as :meth:production_violations — each mixin overrides it cooperatively, calls super() first and appends its own name. The base contributes nothing.

Returns:

Type Description
list[str]

list[str]: Integration names ("storage", "email",

list[str]

"firebase", "revenuecat", "zap"), one per switched-off

list[str]

mixin.

list[str]

The order follows the cooperative super() chain and is not

list[str]

part of the contract — compare as a set. These are the same

list[str]

strings an

list[str]

class:~tempest_fastapi_sdk.exceptions.IntegrationDisabledException

list[str]

carries in details["integration"].

AppSettingsMeta

Bases: ModelMetaclass

Metaclass that validates the position of settings bases.

Every settings mixin the SDK ships subclasses :class:BaseAppSettings, so C3 linearization forbids BaseAppSettings from preceding a mixin in the base list. Python already rejects that, but the message it emits (Cannot create a consistent method resolution order (MRO) for bases BaseAppSettings, RedisSettings) never names the fix, and under the pydantic mypy plugin the same line also reports a misleading [metaclass] error. This metaclass pre-checks the base ordering and raises an instruction instead.

DeprecatedEnvAliasesSettingsSource

DeprecatedEnvAliasesSettingsSource(
    settings_cls: type[BaseSettings],
    sources: tuple[PydanticBaseSettingsSource, ...],
    *,
    enforce_strict: bool = True,
)

Bases: PydanticBaseSettingsSource

Settings source resolving DEPRECATED_ENV_ALIASES and converters.

Placed after env_settings and dotenv_settings by :meth:~tempest_fastapi_sdk.settings.BaseAppSettings.settings_customise_sources. During construction it validates that no deprecated alias or converter conflicts with its canonical name (raising SettingsError without leaking values) and enforces ENV_ALIASES_STRICT when enabled. When called by pydantic-settings, any canonical field not already supplied by a higher-priority source is populated from the resolved deprecated value, prepared with the underlying EnvSettingsSource (so JSON lists, dicts, enums and booleans parse identically), and reported via both a DeprecationWarning and a structured boot log on the tempest_fastapi_sdk.settings logger.

Inspect sources, check conflicts and strict mode, and cache values.

Parameters:

Name Type Description Default
settings_cls type[BaseSettings]

The settings class being built.

required
sources tuple[PydanticBaseSettingsSource, ...]

Environment sources in priority order (typically (env_settings, dotenv_settings)).

required
enforce_strict bool

When True (default), a truthy ENV_ALIASES_STRICT fails construction if any deprecated alias or converter matched.

True

Raises:

Type Description
SettingsError

When a deprecated alias or converter conflicts with its canonical variable, fails to convert, or is matched while ENV_ALIASES_STRICT is enabled.

get_field_value

get_field_value(field: FieldInfo, field_name: str) -> tuple[object, str, bool]

Return the deprecated-alias raw value for field_name if matched.

Parameters:

Name Type Description Default
field FieldInfo

The pydantic field metadata.

required
field_name str

The attribute name on settings_cls.

required

Returns:

Type Description
object

tuple[object, str, bool]: ``(raw_value, field_key,

str

value_is_complex)`` when a deprecated alias or converter supplied

bool

this field, or (None, field_name, False) otherwise.

ENV_ALIASES_STRICT_VAR module-attribute

ENV_ALIASES_STRICT_VAR: str = 'ENV_ALIASES_STRICT'

Environment variable that turns any deprecated env alias or converter match into a startup SettingsError.

EnvAliasConverter module-attribute

EnvAliasConverter: TypeAlias = Callable[[Mapping[str, str]], str | None]

Converter producing one canonical env string from the merged raw environment.

Receives a read-only Mapping[str, str] containing the process environment merged over .env (process values win) and returns either the string value for the canonical field or None when no legacy variable matched.

reject_conflicting_env_aliases

reject_conflicting_env_aliases(
    settings_cls: type[BaseSettings], sources: tuple[PydanticBaseSettingsSource, ...]
) -> None

Refuse a deprecated env var or converter set next to its replacement.

Left alone, STORAGE_SECRET_KEY set by a new deploy script and a stale MINIO_SECRET_KEY in .env would both look configured while only one of them reaches the client. Setting both names (or the canonical name and a converter's output) to the same value is accepted, so a deploy can carry both during a migration window.

Values are compared as the raw strings the sources read, across the environment and the .env file together: the old name in one and the new name in the other still counts as a clash.

Parameters:

Name Type Description Default
settings_cls type[BaseSettings]

The settings class being built; its MRO supplies DEPRECATED_ENV_ALIASES and DEPRECATED_ENV_CONVERTERS.

required
sources tuple[PydanticBaseSettingsSource, ...]

The sources to inspect. Only environment-backed ones (EnvSettingsSource and its .env subclass) are read.

required

Raises:

Type Description
SettingsError

When at least one deprecated alias or converter clashes with its canonical replacement (or another deprecated source for the same field). The message names every clashing pair and never includes a value.

read_project_version

read_project_version(pyproject_path: Path | None = None) -> str

Return the project version declared in a pyproject.toml.

With no argument the search starts at the current working directory and walks up to the filesystem root, stopping at the first pyproject.toml it finds — the same resolution find_pyproject uses. Pass an explicit pyproject_path when the answer must not depend on the working directory: the scaffolded settings module anchors it on its own location, so the version is the project's even when the app is started from somewhere else.

Parameters:

Name Type Description Default
pyproject_path Path | None

The file to read. Defaults to the nearest pyproject.toml above the current working directory.

None

Returns:

Name Type Description
str str

The value of [project].version.

Raises:

Type Description
FileNotFoundError

When no pyproject.toml is found. The message lists every path the search visited, so a miss names what it looked for and where.

ValueError

When the file has no [project].version — an absent [project] table, an absent key, or a project that declares the version through dynamic. The message names the file and the missing key.

kwargs

Typed dictionaries returned by settings *_kwargs() mappers.

Each :class:~typing.TypedDict matches the keyword arguments of the constructor or factory the corresponding mapper is meant to be splatted into (for example EmailUtils(**settings.email_kwargs())). Keeping these definitions in a dedicated module with zero heavy runtime imports lets tempest_fastapi_sdk.settings stay free of optional extras while giving mypy and basedpyright full checking on every ** unpack.

LoggingKwargs

Bases: TypedDict

Keyword arguments for :func:~tempest_fastapi_sdk.configure_logging.

Returned by :meth:~tempest_fastapi_sdk.settings.LogSettings.logging_kwargs.

Attributes:

Name Type Description
level str

Root logger level (LOG_LEVEL).

json_output bool

Emit JSON records to stdout (LOG_JSON).

log_dir str

Directory for log files, or empty to disable file logging (LOG_DIR).

max_bytes int

Size-based rotation threshold in bytes (LOG_MAX_BYTES).

backup_count int

Rotated files kept per level (LOG_BACKUP_COUNT).

rotate_when str | None

Time-based rotation unit, or None for size-based rotation (LOG_ROTATE_WHEN).

rotate_interval int

Number of rotate_when units per period (LOG_ROTATE_INTERVAL).

redact bool

Apply the default redaction policy (LOG_REDACT).

DatabaseKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.AsyncDatabaseManager.

Returned by :meth:~tempest_fastapi_sdk.settings.DatabaseSettings.database_kwargs.

Attributes:

Name Type Description
db_url str

Async SQLAlchemy connection URL (DATABASE_URL).

echo bool

Echo SQL statements (DATABASE_ECHO).

pool_size int

Persistent pool size (DATABASE_POOL_SIZE).

max_overflow int

Pool overflow capacity (DATABASE_MAX_OVERFLOW).

pool_recycle int

Connection recycle interval in seconds (DATABASE_POOL_RECYCLE).

sqlite_wal bool

Enable WAL mode on SQLite (DATABASE_SQLITE_WAL).

sqlite_busy_timeout float

SQLite lock wait timeout in seconds (DATABASE_SQLITE_BUSY_TIMEOUT).

sqlite_foreign_keys bool

Enforce SQLite foreign keys (DATABASE_SQLITE_FOREIGN_KEYS).

RedisKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.cache.AsyncRedisManager.

Returned by :meth:~tempest_fastapi_sdk.settings.RedisSettings.redis_kwargs.

Attributes:

Name Type Description
url str

Redis connection URL (REDIS_URL).

decode_responses bool

Decode bytes to str (REDIS_DECODE_RESPONSES).

JWTKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.JWTUtils.

Returned by :meth:~tempest_fastapi_sdk.settings.JWTSettings.jwt_kwargs.

Attributes:

Name Type Description
secret str

Shared signing secret (JWT_SECRET).

algorithm str

JOSE algorithm identifier (JWT_ALGORITHM).

default_ttl timedelta

Default access-token lifetime derived from JWT_ACCESS_TTL_SECONDS.

issuer str | None

Optional iss claim (JWT_ISSUER).

EmailKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.EmailUtils.

Returned by :meth:~tempest_fastapi_sdk.settings.EmailSettings.email_kwargs.

Attributes:

Name Type Description
host str

SMTP host (SMTP_HOST).

port int

SMTP TCP port (SMTP_PORT).

from_addr str

Default sender address (SMTP_FROM_ADDR).

username str | None

Optional SMTP username (SMTP_USERNAME).

password str | None

Optional SMTP password (SMTP_PASSWORD).

use_tls bool

Implicit TLS from connect (SMTP_USE_SSL).

use_starttls bool

Negotiate STARTTLS after connect (SMTP_USE_TLS).

timeout float

Network timeout in seconds (SMTP_TIMEOUT_SECONDS).

enabled NotRequired[bool]

Present as False when EMAIL_ENABLED is off; omitted when enabled.

UploadKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.UploadUtils.

Returned by :meth:~tempest_fastapi_sdk.settings.UploadSettings.upload_kwargs.

Attributes:

Name Type Description
source str

Root directory for local uploads (UPLOAD_DIR).

max_size_bytes int

Hard file-size limit in bytes (UPLOAD_MAX_SIZE_BYTES).

allowed_extensions set[str]

Allowed lowercase extensions (UPLOAD_ALLOWED_EXTENSIONS).

allowed_mimetypes set[str]

Allowed MIME types (UPLOAD_ALLOWED_MIMETYPES).

WebPushKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.WebPushDispatcher.

Returned by :meth:~tempest_fastapi_sdk.settings.WebPushSettings.webpush_kwargs.

Attributes:

Name Type Description
vapid_private_key str

URL-safe base64 VAPID private key (VAPID_PRIVATE_KEY).

vapid_subject str

mailto: or https:// VAPID subject (VAPID_SUBJECT).

ttl_seconds int

Default notification TTL in seconds (WEBPUSH_DEFAULT_TTL_SECONDS).

FirebaseKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.auth.FirebaseAuth.

Returned by :meth:~tempest_fastapi_sdk.settings.FirebaseSettings.firebase_kwargs. Every key is optional because unset credentials are omitted rather than forwarded as empty strings, and disabling the integration yields only {"enabled": False}.

Attributes:

Name Type Description
credentials_json str

Inline service-account JSON (FIREBASE_CREDENTIALS_JSON).

credentials_path str

Path to a service-account JSON file (FIREBASE_CREDENTIALS_PATH).

project_id str

Firebase project id (FIREBASE_PROJECT_ID).

enabled bool

Present as False when FIREBASE_ENABLED is off.

KafkaKwargs

Bases: TypedDict

Keyword arguments for :meth:~tempest_fastapi_sdk.queue.MessageBroker.kafka.

Returned by :meth:~tempest_fastapi_sdk.settings.KafkaSettings.kafka_kwargs.

Attributes:

Name Type Description
security BaseSecurity | None

FastStream security configuration for the chosen protocol/mechanism, or None under PLAINTEXT.

client_id NotRequired[str]

Optional Kafka client identifier (KAFKA_CLIENT_ID), present only when configured.

GoogleOAuthKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.GoogleOAuthClient.

Returned by :meth:~tempest_fastapi_sdk.settings.OAuthSettings.google_kwargs.

Attributes:

Name Type Description
client_id str

Google OAuth client id (OAUTH_GOOGLE_CLIENT_ID).

client_secret str

Google OAuth client secret (OAUTH_GOOGLE_CLIENT_SECRET).

redirect_uri str

Derived OAuth callback URL.

extra_audiences list[str]

Additional accepted ID-token audiences (OAUTH_GOOGLE_EXTRA_AUDIENCES).

GitHubOAuthKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.GitHubOAuthClient.

Returned by :meth:~tempest_fastapi_sdk.settings.OAuthSettings.github_kwargs.

Attributes:

Name Type Description
client_id str

GitHub OAuth client id (OAUTH_GITHUB_CLIENT_ID).

client_secret str

GitHub OAuth client secret (OAUTH_GITHUB_CLIENT_SECRET).

redirect_uri str

Derived OAuth callback URL.

LocalStorageKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.LocalObjectStorageClient.

Returned by :meth:~tempest_fastapi_sdk.settings.StorageSettings.local_storage_kwargs.

Attributes:

Name Type Description
base_dir str

Local storage root directory (STORAGE_LOCAL_DIR).

public_url str

Public base URL for signed links (STORAGE_LOCAL_PUBLIC_URL).

signing_secret str

Secret signing local upload/download URLs (STORAGE_LOCAL_SIGNING_SECRET).

default_bucket str

Default bucket name (STORAGE_DEFAULT_BUCKET).

route_prefix str

Mount prefix for signed local routes (STORAGE_LOCAL_ROUTE_PREFIX).

max_upload_bytes int

Maximum body size accepted by local PUT (STORAGE_LOCAL_MAX_UPLOAD_BYTES).

encryption_keys NotRequired[dict[str, bytes]]

Decoded 32-byte AES-256-GCM keys, present only when STORAGE_LOCAL_ENCRYPTION_KEYS is non-empty.

allow_plaintext_read NotRequired[bool]

Whether unencrypted files may be read alongside encrypted ones, present only when STORAGE_LOCAL_ENCRYPTION_KEYS is non-empty.

enabled NotRequired[bool]

Present as False when STORAGE_ENABLED is off; omitted when enabled.

StorageKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.AsyncMinIOClient.

Returned by :meth:~tempest_fastapi_sdk.settings.StorageSettings.storage_kwargs and its pre-rename alias :meth:~tempest_fastapi_sdk.settings.StorageSettings.minio_kwargs.

Attributes:

Name Type Description
endpoint str

S3-compatible host[:port] (STORAGE_ENDPOINT).

access_key str

S3 access key (STORAGE_ACCESS_KEY).

secret_key str

S3 secret key (STORAGE_SECRET_KEY).

default_bucket str

Default bucket name (STORAGE_DEFAULT_BUCKET).

secure bool

Use HTTPS for server-side requests (STORAGE_SECURE).

region str

S3 region (STORAGE_REGION).

public_endpoint str | None

Optional public endpoint for presigned URLs (STORAGE_PUBLIC_ENDPOINT).

public_secure bool | None

Optional HTTPS override for presigned URLs (STORAGE_PUBLIC_SECURE).

accel_redirect bool

Deliver objects via nginx X-Accel-Redirect (STORAGE_ACCEL_REDIRECT).

accel_prefix str

Internal nginx location prefix (STORAGE_ACCEL_PREFIX).

enabled NotRequired[bool]

Present as False when STORAGE_ENABLED is off; omitted when enabled.

AnthropicKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.genai.AnthropicGenerator.

Returned by :meth:~tempest_fastapi_sdk.settings.HostedGenAISettings.anthropic_kwargs.

Attributes:

Name Type Description
model str

Anthropic model id (ANTHROPIC_MODEL).

api_key str

Anthropic API key (ANTHROPIC_API_KEY).

base_url str

Anthropic API root URL (ANTHROPIC_BASE_URL).

OpenAIKwargs

Bases: TypedDict

Keyword arguments for OpenAICompatGenerator on OpenAI.

Returned by :meth:~tempest_fastapi_sdk.settings.HostedGenAISettings.openai_kwargs.

Attributes:

Name Type Description
model str

OpenAI model id (OPENAI_MODEL).

api_key str

OpenAI API key (OPENAI_API_KEY).

base_url str

OpenAI API root URL (OPENAI_BASE_URL).

provider str

Provider label ("openai").

max_tokens_field str

Output budget field name ("max_completion_tokens").

structured_output Literal['json_schema', 'json_object']

Structured output wire mode ("json_schema").

OpenAISpeechKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.genai.OpenAICompatSpeech.

Returned by :meth:~tempest_fastapi_sdk.settings.HostedGenAISettings.openai_speech_kwargs.

Attributes:

Name Type Description
model str

OpenAI transcription model id (OPENAI_STT_MODEL).

api_key str

OpenAI API key (OPENAI_API_KEY).

base_url str

OpenAI API root URL (OPENAI_BASE_URL).

provider str

Provider label ("openai").

DeepSeekKwargs

Bases: TypedDict

Keyword arguments for OpenAICompatGenerator on DeepSeek.

Returned by :meth:~tempest_fastapi_sdk.settings.HostedGenAISettings.deepseek_kwargs.

Attributes:

Name Type Description
model str

DeepSeek model id (DEEPSEEK_MODEL).

api_key str

DeepSeek API key (DEEPSEEK_API_KEY).

base_url str

DeepSeek API root URL (DEEPSEEK_BASE_URL).

provider str

Provider label ("deepseek").

structured_output Literal['json_schema', 'json_object']

Structured output wire mode ("json_object").

effort_field str | None

Effort field name (None for DeepSeek).

accepts_documents bool

Whether document parts are supported (False).

GeminiKwargs

Bases: TypedDict

Keyword arguments for OpenAICompatGenerator on Gemini.

Returned by :meth:~tempest_fastapi_sdk.settings.HostedGenAISettings.gemini_kwargs.

Attributes:

Name Type Description
model str

Gemini model id (GOOGLE_MODEL).

api_key str

Gemini API key (GOOGLE_API_KEY).

base_url str

Gemini OpenAI-compatible API root URL (GOOGLE_BASE_URL).

provider str

Provider label ("google").

structured_output Literal['json_schema', 'json_object']

Structured output wire mode ("json_schema").

effort_values Mapping[str, str]

Mapping from SDK effort names to Gemini reasoning_effort values.

accepts_documents bool

Whether document parts are supported (False).

HostedGenAIKwargs

Bases: TypedDict

Keyword arguments for :func:~tempest_fastapi_sdk.genai.hosted_generator.

Returned by :meth:~tempest_fastapi_sdk.settings.HostedGenAISettings.hosted_kwargs.

Attributes:

Name Type Description
model str

Hosted model id.

api_key str

Resolved API key for the provider.

base_url str

Resolved API root URL for the provider.

provider Literal['anthropic', 'openai', 'google', 'deepseek']

Resolved hosted provider key.

HTTPClientKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.HTTPClient.

Returned by :meth:~tempest_fastapi_sdk.settings.OpenPixSettings.openpix_kwargs, :meth:~tempest_fastapi_sdk.settings.MercadoPagoSettings.mercado_pago_kwargs, and :meth:~tempest_fastapi_sdk.settings.RevenueCatSettings.revenuecat_kwargs.

Attributes:

Name Type Description
base_url str

Provider API root URL.

default_headers dict[str, str]

Default HTTP headers carrying the provider's authentication format.

HostBridgeKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.hostbridge.HostBridgeConfig.

Returned by :meth:~tempest_fastapi_sdk.settings.HostBridgeSettings.hostbridge_kwargs.

Attributes:

Name Type Description
allowed_base_paths tuple[str, ...]

Directories the host file surface may access (HOST_ALLOWED_BASE_PATHS).

powershell_binary str

PowerShell executable name (HOST_POWERSHELL_BINARY).

cmd_binary str

cmd executable name (HOST_CMD_BINARY).

default_command_timeout int

Default command timeout in seconds (HOST_COMMAND_TIMEOUT).

max_file_read_bytes int

Ceiling for a single file read in bytes (HOST_MAX_FILE_READ_BYTES).

RemoteHostBridgeKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.hostbridge.RemoteHostBridge.

Returned by :meth:~tempest_fastapi_sdk.settings.HostBridgeSettings.remote_hostbridge_kwargs.

Attributes:

Name Type Description
base_url str

The host agent's origin (HOST_BRIDGE_URL).

token str

Shared secret the agent checks (HOST_BRIDGE_TOKEN).

default_command_timeout int

Default command timeout in seconds, used to size the HTTP timeout (HOST_COMMAND_TIMEOUT).

mixins

Composable settings mixins covering common service dependencies.

Each mixin is a fully-typed Pydantic model with sensible defaults so projects can opt in by listing the mixins they need alongside their own concrete Settings class:

class Settings(DatabaseSettings, RedisSettings, BaseAppSettings):
    ...

Every mixin inherits :class:BaseAppSettings (not raw pydantic_settings.BaseSettings), so each one carries the canonical model_config — env_file=".env", extra="ignore", case_sensitive=True — materialized on its own class. This makes the value of .env loading independent of mixin ordering: pydantic materializes a complete model_config onto every settings class, so a mixin listed before BaseAppSettings would otherwise overwrite the whole config (resetting env_file to None) even though it never declared that key. Inheriting BaseAppSettings keeps .env in the materialized config no matter where the mixin sits.

Because the mixins now subclass BaseAppSettings, BaseAppSettings must be the last base of the composed Settings. Listing it before any mixin violates Python's C3 linearization (a base cannot precede its own subclass) and raises TypeError: Cannot create a consistent method resolution order (MRO) at import — so keep BaseAppSettings at the end of the bases, as shown above.

Every field carries title, description and examples so JSON-Schema consumers (FastAPI /docs, /redoc, IDE tooling, pydantic.model_json_schema()) render rich metadata out of the box.

DEFAULT_LOCAL_STORAGE_ROUTE_PREFIX module-attribute

DEFAULT_LOCAL_STORAGE_ROUTE_PREFIX: str = '/storage'

Path the signed local-storage routes live under by default.

DEFAULT_LOCAL_MAX_UPLOAD_BYTES module-attribute

DEFAULT_LOCAL_MAX_UPLOAD_BYTES: int = 25 * 1024 * 1024

Largest body the signed local-storage PUT accepts by default (25 MiB).

DEV_LOCAL_STORAGE_SIGNING_SECRET module-attribute

DEV_LOCAL_STORAGE_SIGNING_SECRET: str = 'tempest-local-storage-dev-only'

Development placeholder of STORAGE_LOCAL_SIGNING_SECRET.

Public on purpose: the production guard refuses it, so a deployment that forgot to set the secret fails to boot instead of signing forgeable links.

SPOOFABLE_IP_HEADERS module-attribute

SPOOFABLE_IP_HEADERS: frozenset[str] = frozenset({'x-forwarded-for', 'forwarded'})

Header names :class:ServerSettings refuses as TRUSTED_IP_HEADER.

Both are appended to hop by hop rather than overwritten, so their leftmost content is whatever the client sent.

AUTH_EMAIL_LINK_FIELDS: tuple[str, ...] = (
    "AUTH_ACTIVATION_URL_TEMPLATE",
    "AUTH_PASSWORD_RESET_URL_TEMPLATE",
    "AUTH_EMAIL_CHANGE_URL_TEMPLATE",
    "AUTH_EMAIL_VERIFICATION_URL_TEMPLATE",
)

AuthSettings fields whose rendered URL travels inside an auth e-mail.

These are every url_template the UserAuthService passes when it issues a mailed token. AUTH_LOGIN_URL is not here: it is a button on a backend-rendered page, never part of an e-mail.

AppEnvironment module-attribute

AppEnvironment = Literal['development', 'test', 'production']

The deployment environments :class:EnvironmentSettings recognises.

SessionCookieSameSite module-attribute

SessionCookieSameSite = Literal['lax', 'strict', 'none']

The SameSite values Starlette's Response.set_cookie accepts.

EnvironmentSettings

Bases: BaseAppSettings

Deployment environment plus the production guard.

Compose it like any mixin. With ENV=production the settings refuse to build while any composed mixin still holds a development value, listing every offending field at once; with development or test nothing changes::

class Settings(EnvironmentSettings, DatabaseSettings, BaseAppSettings):
    ...

What counts as a development value is declared by each mixin in its :meth:~BaseAppSettings.production_violations override, so the guard only checks the mixins the service actually lists:

  • :class:ServerSettings — SERVER_DEBUG or SERVER_RELOAD on.
  • :class:DatabaseSettings — a SQLite DATABASE_URL.
  • :class:JWTSettings — JWT_SECRET equal to the declared placeholder.
  • :class:CORSSettings — "*" in CORS_ORIGINS.
  • :class:TokenSettings — an empty TOKEN_SECRET.
  • :class:TaskIQSettings — an empty TASKIQ_BROKER_URL.
  • :class:StorageSettings — the MinIO default access or secret key, STORAGE_SECURE off, or STORAGE_PUBLIC_SECURE explicitly off.
  • :class:EmailSettings — a Mailpit/MailHog host, loopback on port 1025, or a placeholder SMTP_FROM_ADDR domain.
  • :class:RevenueCatSettings — both webhook secrets empty.

A third-party integration can be switched off instead of configured (STORAGE_ENABLED, EMAIL_ENABLED, FIREBASE_ENABLED, REVENUECAT_ENABLED set to false): its checks are skipped, the boot succeeds, and :meth:~BaseAppSettings.disabled_integrations names it so the app can log the switch.

The error message names fields and reasons, never values.

ENV has no default. A missing value refuses to build: with a development default, a production host that forgot to set it booted with every development value and the guard never ran.

Attributes:

Name Type Description
ENV AppEnvironment

"development", "test" or "production". Required.

settings_customise_sources classmethod

settings_customise_sources(
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]

Drop the .env source when ENV=test comes from outside it.

A test suite pins ENV=test in the process environment (or passes ENV="test" to the constructor) so it never inherits the developer's configuration. Without this hook the .env in the working directory was still read, and every value the suite did not pin itself -- a real DATABASE_URL, an SMTP host, an API key -- leaked into the tests.

The decision reads only the constructor keyword arguments and the process environment, never the .env itself: ENV=test written in the .env sets the field like any other value and the file is read as usual, because a source cannot be the reason it is discarded. With ENV resolving to anything else, or absent from both, the sources are the ones :meth:BaseAppSettings.settings_customise_sources returns, including the deprecated-alias check.

A Settings class that overrides this hook itself replaces the behaviour; call super().settings_customise_sources(...) from the override to keep it.

Parameters:

Name Type Description Default
settings_cls type[BaseSettings]

The class being built.

required
init_settings PydanticBaseSettingsSource

Keyword arguments passed to the constructor.

required
env_settings PydanticBaseSettingsSource

The process environment.

required
dotenv_settings PydanticBaseSettingsSource

The .env file.

required
file_secret_settings PydanticBaseSettingsSource

The secrets directory.

required

Returns:

Type Description
PydanticBaseSettingsSource

tuple[PydanticBaseSettingsSource, ...]: The sources in

...

priority order, without dotenv_settings when the suite

tuple[PydanticBaseSettingsSource, ...]

pinned ENV=test.

Raises:

Type Description
SettingsError

When a deprecated environment variable and its replacement are both set to different values.

ServerSettings

Bases: BaseAppSettings

HTTP server bind configuration.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
SERVER_HOST str

Interface to bind to. Default: "127.0.0.1".

SERVER_PORT int

TCP port the application listens on. Default: 8000.

SERVER_RELOAD bool

Hot-reload on file changes (dev only). Default: False.

SERVER_DEBUG bool

Generic application debug flag. Default: False.

TRUSTED_IP_HEADER str | None

The single header the edge proxy overwrites with the client address (x-real-ip, cf-connecting-ip), lowercased. None uses the TCP peer. Pass it as trusted_ip_header= to RateLimitMiddleware, AccessLogMiddleware and HoneypotBanMiddleware, and as trusted_header= to get_client_ip. X-Forwarded-For and Forwarded are refused. Default: None.

SERVER_PUBLIC_SCHEME Literal['http', 'https', '']

The scheme the browser uses to reach the service. Pass it as scheme= to PublicSchemeMiddleware so every absolute URL the server builds — the admin login form's action included — comes out in that scheme behind a TLS-terminating proxy. "" keeps the connection's scheme. Default: "".

API_DOCS_LOCALE Literal['en-US', 'pt-BR']

The language the SDK's bundled routers (make_auth_router, make_sse_router, make_health_router, …) write their OpenAPI summary and description in, when the factory is not given docs_locale=. Matched case-insensitively (pt_br, pt resolve to pt-BR); any other language is refused. Default: "en-US".

In ENV=production (see :class:EnvironmentSettings) SERVER_DEBUG and SERVER_RELOAD must be off.

production_violations

production_violations() -> list[str]

Refuse the debug and reload switches in production.

Returns:

Type Description
list[str]

list[str]: The parent's entries plus one per switch left on.

LogSettings

Bases: BaseAppSettings

Structured logging configuration.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
LOG_LEVEL str

Default logger level for configure_logging. Default: "INFO".

LOG_JSON bool

Emit stdout logs as JSON. Default: True.

LOG_DIR str

Directory for per-level + 500.log files; empty disables file logging. Default: "logs".

LOG_MAX_BYTES int

Size at which each log file rotates; 0 disables rotation. Default: 10_000_000.

LOG_BACKUP_COUNT int

Rotated files kept per level. Default: 5.

LOG_ROTATE_WHEN str

Rotate by time instead of size — midnight, H, D, W0-W6, S or M (case-insensitive). Empty keeps size-based rotation. Default: "".

LOG_ROTATE_INTERVAL int

Units of LOG_ROTATE_WHEN per period. Default: 1.

LOG_REDACT bool

Redact e-mails, credentials and sensitive extra= keys from every record with the default :class:~tempest_fastapi_sdk.RedactionPolicy. Default: False.

logging_kwargs

logging_kwargs() -> LoggingKwargs

Map these settings onto :func:configure_logging kwargs.

Without this, a service wires the call by hand and the two rotation knobs are the ones that get left out — they are the newest, and a missing one degrades to a default rather than to an error.

log_dir is passed through as-is, including the empty string, which :func:configure_logging reads as "no file logging". An empty LOG_ROTATE_WHEN becomes rotate_when=None (size-based rotation).

Returns:

Name Type Description
LoggingKwargs LoggingKwargs

Keyword arguments ready to splat into

LoggingKwargs

configure_logging(**settings.logging_kwargs()).

DatabaseSettings

Bases: BaseAppSettings

SQLAlchemy database connection configuration.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
DATABASE_URL str

Async SQLAlchemy connection URL. Default: "sqlite+aiosqlite:///./app.db".

DATABASE_ECHO bool

Print every SQL statement to the logger (dev only). Default: False.

DATABASE_POOL_SIZE int

Number of persistent pool connections. Default: 10.

DATABASE_MAX_OVERFLOW int

Max extra connections opened past the pool size under load. Default: 20.

DATABASE_POOL_RECYCLE int

Seconds before a pooled connection is recycled. Default: 3600.

DATABASE_SQLITE_WAL bool

Put SQLite engines in WAL mode. Ignored on other backends. Default: True.

DATABASE_SQLITE_BUSY_TIMEOUT float

Seconds a SQLite connection waits on a lock before failing. Ignored on other backends. Default: 30.0.

DATABASE_SQLITE_FOREIGN_KEYS bool

Make SQLite enforce FOREIGN KEY constraints and ON DELETE actions. Ignored on other backends. Default: True.

database_kwargs

database_kwargs() -> DatabaseKwargs

Map these settings onto :class:AsyncDatabaseManager kwargs.

Returns:

Name Type Description
DatabaseKwargs DatabaseKwargs

Keyword arguments ready to splat into

DatabaseKwargs

AsyncDatabaseManager(**settings.database_kwargs()).

production_violations

production_violations() -> list[str]

Refuse SQLite as the production database.

Returns:

Type Description
list[str]

list[str]: The parent's entries plus one when

list[str]

DATABASE_URL uses a sqlite dialect.

RedisSettings

Bases: BaseAppSettings

Redis connection configuration.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
REDIS_URL str

redis://[user:pass@]host:port/db connection URL. Default: "redis://localhost:6379/0".

REDIS_DECODE_RESPONSES bool

Decode bytes to str automatically. Default: True.

redis_kwargs

redis_kwargs() -> RedisKwargs

Map these settings onto :class:AsyncRedisManager kwargs.

Returns:

Name Type Description
RedisKwargs RedisKwargs

Keyword arguments ready to splat into

RedisKwargs

AsyncRedisManager(**settings.redis_kwargs()).

RabbitMQSettings

Bases: BaseAppSettings

RabbitMQ / FastStream broker configuration.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
RABBITMQ_URL str

amqp://user:pass@host:port/vhost connection URL. Default: "amqp://guest:guest@localhost:5672/".

RABBITMQ_PREFETCH_COUNT int

Number of unacked messages a consumer can hold. Default: 10.

JWTSettings

Bases: BaseAppSettings

JWT signing and verification configuration.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
JWT_SECRET str

Shared secret used to sign JWTs (>= 32 bytes for HS256). Default: "change-me-change-me-change-me-32".

JWT_ALGORITHM str

JOSE algorithm used to sign and verify tokens. Default: "HS256".

JWT_ACCESS_TTL_SECONDS int

Lifetime of issued access tokens. Default: 3600.

JWT_REFRESH_TTL_SECONDS int

Lifetime of issued refresh tokens. Default: 604800.

JWT_ISSUER str | None

Value of the iss claim; None omits it. Default: None.

jwt_kwargs

jwt_kwargs() -> JWTKwargs

Map these settings onto :class:JWTUtils constructor kwargs.

JWT_ACCESS_TTL_SECONDS becomes the default_ttl timedelta; the refresh TTL is not a JWTUtils parameter (it is consumed by the bundled auth flow) and is intentionally left out.

Returns:

Name Type Description
JWTKwargs JWTKwargs

Keyword arguments ready to splat into

JWTKwargs

JWTUtils(**settings.jwt_kwargs()).

production_violations

production_violations() -> list[str]

Refuse the placeholder signing secret in production.

The placeholder is read from JWTSettings.model_fields — the default this mixin declares — rather than from a copied literal, so changing the default cannot leave the check comparing against a string the SDK stopped shipping.

Returns:

Type Description
list[str]

list[str]: The parent's entries plus one when JWT_SECRET

list[str]

still equals the mixin's declared default.

CORSSettings

Bases: BaseAppSettings

CORS middleware configuration.

.. warning:: The default CORS_ORIGINS=["*"] is permissive on purpose so local development works out of the box. Never ship this default to production — set CORS_ORIGINS to the explicit list of trusted frontend origins. Do not combine "*" with CORS_ALLOW_CREDENTIALS=True: Starlette's CORSMiddleware then answers every request with the caller's own Origin plus Access-Control-Allow-Credentials: true, so every site may make credentialed reads. With ENV=production (:class:EnvironmentSettings) the settings refuse to build in that case, and also when credentials are allowed together with a CORS_ORIGIN_REGEX that accepts arbitrary origins or with the "null" origin. Development and test builds keep accepting the pair.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
CORS_ORIGINS list[str]

Allowed origins; override in production. Default: ["*"].

CORS_ORIGIN_REGEX str

Regex matched against the request Origin for session-varying origins (dev tunnels, preview deploys). Empty disables it. Default: "".

CORS_ALLOW_CREDENTIALS bool

Allow cookies / auth headers cross-origin. Default: False.

CORS_ALLOW_METHODS list[str]

HTTP verbs accepted by the preflight check. Default: ["*"].

CORS_ALLOW_HEADERS list[str]

Request headers accepted by the preflight check. Default: ["*"].

CORS_EXPOSE_HEADERS list[str]

Headers exposed to browser JavaScript. Default: ["X-Request-ID"].

CORS_MAX_AGE int

How long the browser may cache the preflight response (seconds). Default: 600.

production_violations

production_violations() -> list[str]

Refuse wildcard and credential-reflecting origins in production.

With CORS_ALLOW_CREDENTIALS=True, Starlette's CORSMiddleware answers an accepted origin with that exact Origin plus Access-Control-Allow-Credentials: true. Any rule that accepts origins nobody listed therefore hands credentialed cross-origin reads to arbitrary sites: "*" in CORS_ORIGINS, a CORS_ORIGIN_REGEX that fully matches a reserved .invalid probe origin (:data:_CORS_PROBE_ORIGINS), and the "null" origin that sandboxed iframes and data: documents send. A regex that does not compile is left to the middleware, which raises on it.

Returns:

Type Description
list[str]

list[str]: The parent's entries plus one per offending rule.

EmailSettings

Bases: BaseAppSettings

SMTP / transactional email configuration.

Mirrors the constructor arguments of :class:tempest_fastapi_sdk.EmailUtils so a service can wire it up with EmailUtils(**settings.email_kwargs()).

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
SMTP_HOST str

Hostname of the SMTP server. Default: "localhost".

SMTP_PORT int

TCP port for the SMTP connection. Default: 587.

SMTP_USERNAME str | None

Auth username; None disables SMTP auth. Default: None.

SMTP_PASSWORD str | None

Auth password, paired with the username. Default: None.

SMTP_FROM_ADDR str

Default From address when the caller omits one. Default: "noreply@example.com".

SMTP_USE_TLS bool

Negotiate STARTTLS after connect (port 587). Default: True.

SMTP_USE_SSL bool

Wrap the connection in TLS from the start (SMTPS, port 465). Default: False.

SMTP_TIMEOUT_SECONDS float

Network timeout for SMTP operations. Default: 30.0.

EMAIL_ENABLED bool

Kill-switch for the whole integration. False skips the production checks below, lists "email" in :meth:disabled_integrations and makes :meth:email_kwargs build an :class:EmailUtils whose every send raises IntegrationDisabledException (503). Default: True.

In ENV=production (see :class:EnvironmentSettings), with EMAIL_ENABLED on, three values are refused because they can only be a development setup:

  • SMTP_HOST whose first DNS label is mailpit or mailhog;
  • SMTP_PORT=1025 together with a loopback SMTP_HOST (localhost, 127.0.0.1, ::1) — the port Mailpit and MailHog publish;
  • SMTP_HOST still at its declared default (localhost) with no SMTP_USERNAME — an unauthenticated default is the development catcher, not a configured relay. A local relay keeps booting by setting SMTP_USERNAME or addressing it as 127.0.0.1;
  • SMTP_FROM_ADDR that is empty, has no @, or whose domain is reserved and can never send real mail: example.com, example.net, example.org or localhost (and any subdomain of them), or anything under .example, .invalid, .localhost or .test. The declared default (noreply@example.com) is refused by itself as well;
  • a TLS mode that contradicts itself or the port: SMTP_USE_SSL and SMTP_USE_TLS both on; SMTP_USE_SSL=true on 587 (implicit TLS against the STARTTLS port — the handshake fails with [SSL: WRONG_VERSION_NUMBER] on every send); SMTP_USE_TLS=true on 465 (STARTTLS against a port that expects TLS from the first byte). Other ports are not judged: a custom relay picks its own.

Gmail (smtp.gmail.com:587, STARTTLS, an app password in SMTP_USERNAME/SMTP_PASSWORD, a real SMTP_FROM_ADDR) produces no violation.

email_kwargs

email_kwargs() -> EmailKwargs

Map these settings onto :class:EmailUtils constructor kwargs.

The setting names follow SMTP conventions while :class:tempest_fastapi_sdk.EmailUtils uses transport-oriented names, so this method bridges the two:

  • SMTP_USE_TLS (STARTTLS after connect, port 587) maps to use_starttls.
  • SMTP_USE_SSL (implicit TLS from connect, port 465) maps to use_tls.

With EMAIL_ENABLED off the dictionary also carries enabled=False, so the same construction line builds a mailer that refuses every send with IntegrationDisabledException instead of connecting to the development default. The key is absent while the integration is on, so the dictionary of a deployment that never touches the flag is unchanged.

Returns:

Name Type Description
EmailKwargs EmailKwargs

Keyword arguments ready to splat into

EmailKwargs

EmailUtils(**settings.email_kwargs()).

Example:

>>> from tempest_fastapi_sdk import EmailUtils
>>> mailer = EmailUtils(**settings.email_kwargs())

production_violations

production_violations() -> list[str]

Refuse a dev mail catcher, a placeholder sender or a TLS mismatch.

Skipped entirely when EMAIL_ENABLED is off. The declared defaults compared against are read from EmailSettings.model_fields, not copied literals. localhost is refused only paired with port 1025 or as the untouched default without SMTP_USERNAME, so an authenticated local relay (or one addressed as 127.0.0.1) keeps booting. The rule is listed in the class docstring.

Returns:

Type Description
list[str]

list[str]: The parent's entries plus one per offending field.

disabled_integrations

disabled_integrations() -> list[str]

Append "email" when EMAIL_ENABLED is off.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus "email" when off.

UploadSettings

Bases: BaseAppSettings

File upload constraints.

Mirrors the constructor arguments of :class:tempest_fastapi_sdk.UploadUtils.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
UPLOAD_DIR str

Root directory where uploaded files are persisted. Default: "./var/uploads".

UPLOAD_MAX_SIZE_BYTES int

Hard limit per file; 0 disables the check. Default: 10485760.

UPLOAD_ALLOWED_EXTENSIONS set[str]

Allowed lowercase extensions; empty means any. Default: set().

UPLOAD_ALLOWED_MIMETYPES set[str]

Allowed MIME types; empty means any. Default: set().

upload_kwargs

upload_kwargs() -> UploadKwargs

Map these settings onto :class:UploadUtils constructor kwargs.

Uses UPLOAD_DIR as the local-disk source; pass an AsyncMinIOClient to UploadUtils directly when storing in a bucket instead.

Returns:

Name Type Description
UploadKwargs UploadKwargs

Keyword arguments ready to splat into

UploadKwargs

UploadUtils(**settings.upload_kwargs()).

TokenSettings

Bases: BaseAppSettings

Shared-secret X-Token configuration.

Used by :func:tempest_fastapi_sdk.make_token_dependency for internal service-to-service authentication. Validation is performed with :func:hmac.compare_digest.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
TOKEN_SECRET str

Expected X-Token header value. Empty makes :func:~tempest_fastapi_sdk.make_token_dependency raise unless the caller passes allow_unauthenticated=True. Default: "".

production_violations

production_violations() -> list[str]

Refuse an empty shared secret in production.

An empty TOKEN_SECRET passed with allow_unauthenticated=True turns :func:~tempest_fastapi_sdk.make_token_dependency into a gate that lets every request through; production refuses that pair.

Returns:

Type Description
list[str]

list[str]: The parent's entries plus one when

list[str]

TOKEN_SECRET is empty.

WebPushSettings

Bases: BaseAppSettings

Web Push / VAPID configuration.

Mirrors the constructor arguments of :class:tempest_fastapi_sdk.WebPushDispatcher.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
VAPID_PUBLIC_KEY str

URL-safe base64 VAPID public key. Default: "".

VAPID_PRIVATE_KEY str

URL-safe base64 VAPID private key. Default: "".

VAPID_SUBJECT str

mailto: / https:// contact in the VAPID JWT. Default: "mailto:admin@example.com". Checked when VAPID_PRIVATE_KEY is set (see :meth:_check_vapid_subject).

WEBPUSH_DEFAULT_TTL_SECONDS int

Default TTL for outgoing notifications. Default: 86400.

webpush_enabled property

webpush_enabled: bool

Whether Web Push dispatch is configured.

Dispatch needs a signing key; with an empty VAPID_PRIVATE_KEY (the dev default) subscribe/unsubscribe still work but sending is skipped. Use this to gate notify calls.

Named for its channel: up to 0.352.0 it was enabled, the same name :class:FirebaseSettings used for FCM, and a service composing both mixins without :class:PushSettings read whichever came first in the MRO (#742).

Returns:

Name Type Description
bool bool

True when a VAPID private key is set.

webpush_kwargs

webpush_kwargs() -> WebPushKwargs

Map these settings onto :class:WebPushDispatcher kwargs.

The public key is advertised to browser clients, not passed to the dispatcher, so it is intentionally omitted here.

Returns:

Name Type Description
WebPushKwargs WebPushKwargs

Keyword arguments ready to splat into

WebPushKwargs

WebPushDispatcher(**settings.webpush_kwargs()).

FirebaseSettings

Bases: BaseAppSettings

Firebase Admin credentials for ID token verification.

Mirrors the constructor arguments of :class:tempest_fastapi_sdk.auth.FirebaseAuth.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

FIREBASE_CREDENTIALS_JSON and FIREBASE_CREDENTIALS_PATH describe the same service account through different channels: the file is the usual local shape, the inline JSON is what a deployment without a mounted volume injects. When both are set the inline JSON wins, matching :class:~tempest_fastapi_sdk.auth.FirebaseAuth. Leaving both empty falls back to the environment's application-default credential.

Attributes:

Name Type Description
FIREBASE_PROJECT_ID str

Firebase project id. Optional when the service account already carries it. Default: "".

FIREBASE_CREDENTIALS_PATH str

Path to a service-account JSON file. Default: "".

FIREBASE_CREDENTIALS_JSON str

The service-account JSON inline. Default: "".

FIREBASE_ENABLED bool

Kill-switch for the whole integration. False makes :attr:enabled answer False whatever the credentials say (so push wiring gated on it builds no FCM transport), lists "firebase" in :meth:disabled_integrations, and makes :meth:firebase_kwargs build a FirebaseAuth that never initializes an app and refuses every verification with IntegrationDisabledException (503). Default: True.

firebase_enabled property

firebase_enabled: bool

Whether Firebase is switched on and has an explicit service account.

False when FIREBASE_ENABLED is off, whatever the credentials say. With the flag on, False does not mean verification is impossible: an application-default credential (GOOGLE_APPLICATION_CREDENTIALS or the metadata server on Google infrastructure) still works. Use this to gate wiring in projects that must run without Firebase at all.

Named for its channel: up to 0.352.0 it was enabled, shared with :class:WebPushSettings (#742).

Returns:

Name Type Description
bool bool

True when FIREBASE_ENABLED is on and a

bool

credentials path or inline JSON is set.

firebase_kwargs

firebase_kwargs() -> FirebaseKwargs

Map these settings onto :class:FirebaseAuth kwargs.

Empty strings are dropped rather than forwarded, so an unset variable leaves the corresponding constructor default in place instead of configuring an empty path.

With FIREBASE_ENABLED off the result is {"enabled": False} and nothing else: the credentials are not forwarded, so the FirebaseAuth it builds never initializes an app (nor falls back to an application-default credential) and refuses every verification with IntegrationDisabledException.

Returns:

Name Type Description
FirebaseKwargs FirebaseKwargs

Keyword arguments ready to splat into

FirebaseKwargs

FirebaseAuth(**settings.firebase_kwargs()).

disabled_integrations

disabled_integrations() -> list[str]

Append "firebase" when FIREBASE_ENABLED is off.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus "firebase" when off.

PushSettings

Bases: WebPushSettings, FirebaseSettings

Every variable a service delivering to browsers and phones needs.

Composing :class:WebPushSettings and :class:FirebaseSettings by hand works too: each half answers through its own name (:attr:~WebPushSettings.webpush_enabled, :attr:~FirebaseSettings.firebase_enabled). This class adds the question neither half can answer — enabled, "can this service push at all" — plus :attr:web_enabled / :attr:mobile_enabled, the platform names the push recipe uses.

Attributes:

Name Type Description
VAPID_PUBLIC_KEY str

Inherited from :class:WebPushSettings.

VAPID_PRIVATE_KEY str

Inherited from :class:WebPushSettings.

VAPID_SUBJECT str

Inherited from :class:WebPushSettings.

WEBPUSH_DEFAULT_TTL_SECONDS int

Inherited from :class:WebPushSettings.

FIREBASE_PROJECT_ID str

Inherited from :class:FirebaseSettings.

FIREBASE_CREDENTIALS_PATH str

Inherited from :class:FirebaseSettings.

FIREBASE_CREDENTIALS_JSON str

Inherited from :class:FirebaseSettings.

web_enabled property

web_enabled: bool

Whether Web Push dispatch is configured.

Returns:

Name Type Description
bool bool

True when a VAPID private key is set.

mobile_enabled property

mobile_enabled: bool

Whether Firebase is switched on and has an explicit service account.

False when FIREBASE_ENABLED is off. With the flag on, False does not mean FCM is impossible — an application-default credential still works. It means this process was not handed one explicitly.

Returns:

Name Type Description
bool bool

True when FIREBASE_ENABLED is on and a

bool

credentials path or inline JSON is set.

enabled property

enabled: bool

Whether the service can push to at least one platform.

Returns:

Name Type Description
bool bool

True when either half is configured.

KafkaSecurityProtocolEnum

Bases: BaseStrEnum

How a Kafka client reaches the brokers (Kafka's security.protocol).

Attributes:

Name Type Description
PLAINTEXT

No TLS, no authentication. The development default.

SSL

TLS, optionally with a client certificate (mutual TLS).

SASL_PLAINTEXT

SASL authentication over an unencrypted connection: the PLAIN mechanism sends the password in clear.

SASL_SSL

SASL authentication over TLS.

KafkaSaslMechanismEnum

Bases: BaseStrEnum

Which SASL mechanism authenticates the client (sasl.mechanism).

Read only when :class:KafkaSecurityProtocolEnum is one of the SASL_* protocols.

Attributes:

Name Type Description
PLAIN

Username and password, sent as they are; only safe over TLS.

SCRAM_SHA_256

Salted challenge-response with SHA-256.

SCRAM_SHA_512

Salted challenge-response with SHA-512.

KafkaSettings

Bases: BaseAppSettings

Kafka connection configuration for :meth:MessageBroker.kafka.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix). The defaults reach a local broker on localhost:9092 with no TLS and no authentication.

The transport security is chosen by KAFKA_SECURITY_PROTOCOL and translated by :meth:kafka_kwargs into the FastStream security object (faststream.security) the broker expects, so the service never builds an ssl.SSLContext or picks a SASL class by hand.

Attributes:

Name Type Description
KAFKA_BOOTSTRAP_SERVERS list[str]

host:port seeds, as a JSON list. Default: ["localhost:9092"].

KAFKA_CLIENT_ID str | None

Name the client reports to the brokers (logs, quotas). None keeps FastStream's default. Default: None.

KAFKA_SECURITY_PROTOCOL KafkaSecurityProtocolEnum

Transport security. Default: PLAINTEXT.

KAFKA_SASL_MECHANISM KafkaSaslMechanismEnum

SASL mechanism, read under SASL_PLAINTEXT / SASL_SSL. Default: PLAIN.

KAFKA_SASL_USERNAME str

SASL username; required under a SASL_* protocol. Default: "".

KAFKA_SASL_PASSWORD SecretStr

SASL password; masked in repr and str. Default: empty.

KAFKA_SSL_CAFILE str | None

PEM bundle of the CAs that sign the broker certificate. None trusts the system store. Default: None.

KAFKA_SSL_CERTFILE str | None

PEM client certificate, for mutual TLS. Default: None.

KAFKA_SSL_KEYFILE str | None

PEM private key of the client certificate; None reads it from KAFKA_SSL_CERTFILE. Default: None.

KAFKA_SSL_KEY_PASSWORD SecretStr

Password of an encrypted KAFKA_SSL_KEYFILE; empty for an unencrypted key. Default: empty.

kafka_ssl_context

kafka_ssl_context() -> SSLContext | None

Build the TLS context the selected protocol needs.

Starts from :func:ssl.create_default_context, so the broker certificate and host name are verified, trusting KAFKA_SSL_CAFILE when set and the system store otherwise. KAFKA_SSL_CERTFILE (with KAFKA_SSL_KEYFILE and KAFKA_SSL_KEY_PASSWORD) adds the client certificate of mutual TLS.

Returns:

Type Description
SSLContext | None

ssl.SSLContext | None: The context under SSL /

SSLContext | None

SASL_SSL; None under the protocols without TLS.

Raises:

Type Description
FileNotFoundError

When a configured file does not exist.

SSLError

When a file is not valid PEM, or the key does not match the certificate.

kafka_kwargs

kafka_kwargs() -> KafkaKwargs

Map these settings onto :meth:MessageBroker.kafka keyword arguments.

The seeds are positional on :meth:MessageBroker.kafka, so they are not in the mapping: MessageBroker.kafka(*settings.KAFKA_BOOTSTRAP_SERVERS, **settings.kafka_kwargs()), or :meth:MessageBroker.kafka_from_settings, which does exactly that.

security is the FastStream object for the protocol and mechanism: None under PLAINTEXT, BaseSecurity under SSL, and SASLPlaintext / SASLScram256 / SASLScram512 under the SASL_* protocols, carrying the TLS context under SASL_SSL. FastStream is imported here, not at module level, so the mixin imports without the [queue-kafka] extra.

Returns:

Name Type Description
KafkaKwargs KafkaKwargs

{"security": ...}, plus "client_id"

KafkaKwargs

when KAFKA_CLIENT_ID is set.

Raises:

Type Description
ImportError

When faststream is not installed and the protocol needs a security object.

production_violations

production_violations() -> list[str]

Refuse a Kafka password that travels or is stored in clear.

Returns:

Type Description
list[str]

list[str]: The parent's entries plus one when the protocol is

list[str]

SASL_PLAINTEXT with the PLAIN mechanism (the password

list[str]

crosses the network unencrypted), and one when a SASL_*

list[str]

protocol has an empty KAFKA_SASL_PASSWORD.

TaskIQSettings

Bases: BaseAppSettings

TaskIQ broker / result backend configuration.

Use this when the TaskIQ broker is not the same RabbitMQ / Redis instance covered by :class:RabbitMQSettings / :class:RedisSettings.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
TASKIQ_BROKER_URL str

URL of the TaskIQ broker (AMQP, Redis, in-memory). Default: "amqp://guest:guest@localhost:5672/".

TASKIQ_RESULT_BACKEND_URL str | None

Optional result backend URL; None keeps results in-memory. Default: None.

TASKIQ_STORE_RESULTS bool

Whether task results are stored at all. Default: True. False leaves TaskIQ's DummyResultBackend in place on both transports — the shape of a cron-only service, where no caller waits on a return value.

TASKIQ_RESULT_TTL_SECONDS int

Seconds a stored result survives. Default: 86400 (one day); 0 keeps results forever, which is what taskiq_redis does on its own.

TASKIQ_WORKER_HEARTBEAT_FILE str

File the worker rewrites each time it runs the heartbeat task; empty disables it. Default: "".

TASKIQ_SCHEDULER_HEARTBEAT_FILE str

File the scheduler rewrites each time it sends the heartbeat task; empty disables it. Default: "".

TASKIQ_HEARTBEAT_SECONDS int

Heartbeat period. Default: 30.

production_violations

production_violations() -> list[str]

Refuse an empty broker URL in production.

:meth:~tempest_fastapi_sdk.tasks.TaskQueue.from_settings turns an empty TASKIQ_BROKER_URL into the in-memory broker, whose enqueue runs the task inside the web process instead of handing it to a worker.

Returns:

Type Description
list[str]

list[str]: The parent's entries plus one when

list[str]

TASKIQ_BROKER_URL is empty.

AuthSettings

Bases: BaseAppSettings

Configuration for the bundled signup / activation / reset flows.

Consumed by :class:tempest_fastapi_sdk.auth.UserAuthService and :func:tempest_fastapi_sdk.make_auth_router. Each flag has a sensible production default; flip AUTH_AUTO_ACTIVATE or AUTH_RETURN_TOKEN_IN_RESPONSE only in dev / CI.

Without :class:EnvironmentSettings composed, the service reads the ENV environment variable to decide whether a link may travel in the response body, and treats an unset ENV as production.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
AUTH_SIGNUP_ENABLED bool

Kill-switch mounting POST /auth/signup. Default: True.

AUTH_AUTO_ACTIVATE bool

Mark users active on signup, skipping the activation email. Default: False.

AUTH_RETURN_TOKEN_IN_RESPONSE bool

Include the activation / reset link in the JSON response. Default: False.

AUTH_ACTIVATION_TTL_SECONDS int

How long an activation token stays valid. Default: 604800.

AUTH_PASSWORD_RESET_TTL_SECONDS int

How long a password-reset token stays valid. Default: 3600.

AUTH_ACTIVATION_URL_TEMPLATE str

Front-end activation URL; {token} is substituted. Default: "http://localhost:3000/activate?token={token}".

AUTH_PASSWORD_RESET_URL_TEMPLATE str

Front-end reset URL; {token} is substituted. Default: "http://localhost:3000/reset-password?token={token}".

AUTH_ACTIVATION_TEMPLATE str

Jinja2 activation email template filename. Default: "activation.html".

AUTH_PASSWORD_RESET_TEMPLATE str

Jinja2 password-reset email template filename. Default: "password_reset.html".

AUTH_EMAIL_BRAND_NAME str

Name in the header of the bundled emails. Empty (default) leaves the header out.

AUTH_EMAIL_BRAND_COLOR str

Hex color of the email button and accents. Default: "#2563eb".

AUTH_EMAIL_BRAND_LOGO_URL str

Absolute http(s) URL of a logo shown in the email header instead of the name. Empty (default) shows the name.

AUTH_EMAIL_FOOTER_TEXT str

Extra line in the email footer (company, address). Empty by default.

AUTH_PASSWORD_MIN_LENGTH int

Minimum accepted password length. Default: 12.

AUTH_PASSWORD_MAX_BYTES int

Maximum accepted password length in UTF-8 bytes. Default: 72 (the bcrypt limit).

AUTH_PASSWORD_REQUIRE_COMPLEXITY bool

Require character-class complexity (and >= 8 length). Default: False.

AUTH_BACKEND_LINKS bool

Mount backend-rendered activation/reset HTML pages. Default: False.

AUTH_LOGIN_URL str | None

Login URL shown on backend success pages; None hides the button. Default: None.

AUTH_ACTIVATION_SUCCESS_TEMPLATE str

Backend activation success page template. Default: "activation_success.html".

AUTH_ACTIVATION_ERROR_TEMPLATE str

Backend activation error page template. Default: "activation_error.html".

AUTH_PASSWORD_RESET_FORM_TEMPLATE str

Backend reset form page template. Default: "password_reset_form.html".

AUTH_PASSWORD_RESET_SUCCESS_TEMPLATE str

Backend reset success page template. Default: "password_reset_success.html".

AUTH_PASSWORD_RESET_ERROR_TEMPLATE str

Backend reset error page template. Default: "password_reset_error.html".

AUTH_PAGES_PREFIX str

Mount prefix of make_auth_pages_router. Default: "" (site root).

AUTH_PAGES_LOGIN_REDIRECT str

Path the pages redirect to after a login without next. Default: "/".

AUTH_PAGES_LOGOUT_REDIRECT str | None

Path after logout; None goes to the login page. Default: None.

AUTH_LOGIN_PAGE_TEMPLATE str

Login page template. Default: "login.html".

AUTH_LOGIN_MFA_PAGE_TEMPLATE str

Second-factor page template. Default: "login_mfa.html".

AUTH_SIGNUP_PAGE_TEMPLATE str

Signup page template. Default: "signup.html".

AUTH_SIGNUP_DONE_TEMPLATE str

"Check your e-mail" page template. Default: "signup_done.html".

AUTH_ACTIVATION_REQUEST_PAGE_TEMPLATE str

Resend-activation page template. Default: "activation_request.html".

AUTH_ACTIVATION_REQUEST_DONE_TEMPLATE str

Resend-activation confirmation template. Default: "activation_request_done.html".

AUTH_MFA_ENABLED bool

Kill-switch enabling the MFA endpoints and TOTP login flow. Default: False.

AUTH_MFA_ISSUER str

Issuer label shown in the Authenticator app. Default: "Tempest".

AUTH_MFA_RECOVERY_CODES_COUNT int

Number of single-use recovery codes generated at enrollment. Default: 10.

AUTH_MFA_TOKEN_TTL_SECONDS int

Lifetime of the intermediate MFA login token. Default: 300.

AUTH_MFA_VERIFY_WINDOW int

TOTP clock-drift tolerance in 30s steps. Default: 1.

AUTH_WEBAUTHN_ENABLED bool

Kill-switch enabling the WebAuthn / passkey endpoints. Default: False.

AUTH_WEBAUTHN_RP_ID str

Domain the credential is bound to. Default: "".

AUTH_WEBAUTHN_RP_NAME str

Product name shown by the browser. Default: "Tempest".

AUTH_WEBAUTHN_ALLOWED_ORIGINS list[str]

Exact origins allowed to complete a ceremony. Default: [] (the fido2 rule).

AUTH_WEBAUTHN_USER_VERIFICATION str

Whether the authenticator must verify the user. Default: "preferred".

AUTH_WEBAUTHN_RESIDENT_KEY str

Whether the credential must be discoverable. Default: "preferred".

AUTH_WEBAUTHN_CHALLENGE_TTL_SECONDS int

Lifetime of the between-request ceremony state. Default: 300.

AUTH_SINGLE_ACTIVE_TOKEN bool

Issuing an account token spends the user's other unused tokens of the same purpose, so only the newest link works. Default: True.

AUTH_OAUTH_ENABLED bool

Kill-switch enabling the social-login (/auth/oauth/*) endpoints. Default: False.

AUTH_OAUTH_STATE_COOKIE_NAME str

Cookie carrying the CSRF state between the redirect and the callback. Default: "oauth_state".

AUTH_OAUTH_STATE_TTL_SECONDS int

Lifetime of that state. Default: 600.

AUTH_OAUTH_LINK_BY_VERIFIED_EMAIL bool

Attach a new provider identity to an existing account when the provider states the email is verified. Default: False.

AUTH_OAUTH_ALLOW_ACCOUNT_CREATION bool | None

Whether the callback may create a user row. Default: None (inherits AUTH_SIGNUP_ENABLED).

production_violations

production_violations() -> list[str]

Refuse e-mailed links that a real user could not open.

Every field in :data:AUTH_EMAIL_LINK_FIELDS is checked with :func:email_link_violation: the host must be reachable from outside (not localhost, loopback, 0.0.0.0 or a reserved name) and the scheme must be https. The defaults (http://localhost:3000/...) fail both.

Skipped when the e-mail integration cannot send — EMAIL_ENABLED off on a composed :class:EmailSettings — because the link then never leaves the process. Without EmailSettings composed the attribute is absent and the check applies.

AUTH_RETURN_TOKEN_IN_RESPONSE is refused regardless of EMAIL_ENABLED: it hands the activation, reset, e-mail change and recovery links to whoever sent the request. AUTH_AUTO_ACTIVATE is refused the same way: it activates every signup without proof that the address belongs to whoever signed up.

Returns:

Type Description
list[str]

list[str]: The parent's entries, one for

list[str]

AUTH_AUTO_ACTIVATE and one for

list[str]

AUTH_RETURN_TOKEN_IN_RESPONSE when each is on, plus at most

list[str]

one per template.

OAuthSettings

Bases: BaseAppSettings

Credentials for the bundled social-login providers.

Splits cleanly from :class:AuthSettings along one line: this mixin says who you are at the provider, and the AUTH_OAUTH_* fields of AuthSettings say what the bundled router does. The router never reads this mixin — it receives clients the application already built — so a project that gets its credentials from a secret manager instead of the environment can skip it entirely and still use every /auth/oauth/* endpoint.

The redirect URI is derived rather than declared. It has to match what is registered at the provider byte for byte, and it is fully determined by the public base URL, the router prefix and the provider key — so declaring it separately is one more string to keep in sync for no gained freedom. Give the base URL; take the callback from :meth:oauth_redirect_uri.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
OAUTH_REDIRECT_BASE_URL str

Public origin the provider will redirect back to, scheme included and no trailing path (e.g. "https://api.example.com"). Default: "".

OAUTH_GOOGLE_CLIENT_ID str

OAuth client id from the Google Cloud console. Default: "".

OAUTH_GOOGLE_CLIENT_SECRET str

Matching client secret. Default: "".

OAUTH_GOOGLE_EXTRA_AUDIENCES list[str]

The project's other Google client ids — the Android and iOS ones — whose tokens POST /auth/oauth/google/token accepts. Default: [].

OAUTH_GITHUB_CLIENT_ID str

Client id of the GitHub OAuth app. Default: "".

OAUTH_GITHUB_CLIENT_SECRET str

Matching client secret. Default: "".

oauth_redirect_uri

oauth_redirect_uri(provider: str, *, prefix: str = '/auth') -> str

Build the callback URL to register with provider.

The value must match the provider's registered redirect URI exactly — a trailing slash or an http where the console holds https is rejected at the authorize step, before the user ever sees a consent screen, which makes it look like a credential problem. Deriving it here keeps the string that reaches the provider and the string the router serves as one expression.

Parameters:

Name Type Description Default
provider str

Provider key as the router routes it ("google", "github", or whatever key the application registered an OIDCProvider under).

required
prefix str

The make_auth_router prefix. Defaults to "/auth"; pass the same value you passed the router if you changed it.

'/auth'

Returns:

Name Type Description
str str

The absolute callback URL.

google_kwargs

google_kwargs(*, prefix: str = '/auth') -> GoogleOAuthKwargs

Map these settings onto GoogleOAuthClient.

from tempest_fastapi_sdk import GoogleOAuthClient

client: GoogleOAuthClient = GoogleOAuthClient(**settings.google_kwargs())

Parameters:

Name Type Description Default
prefix str

The make_auth_router prefix, forwarded to :meth:oauth_redirect_uri. Defaults to "/auth".

'/auth'

Returns:

Name Type Description
GoogleOAuthKwargs GoogleOAuthKwargs

client_id, client_secret, the derived

GoogleOAuthKwargs

redirect_uri and extra_audiences — the last one being

GoogleOAuthKwargs

what lets a token minted by this project's Android or iOS

GoogleOAuthKwargs

client pass the token-in-hand endpoint's audience check.

GoogleOAuthKwargs

Scopes are left to the client's own defaults

GoogleOAuthKwargs

(openid email profile).

github_kwargs

github_kwargs(*, prefix: str = '/auth') -> GitHubOAuthKwargs

Map these settings onto GitHubOAuthClient.

Parameters:

Name Type Description Default
prefix str

The make_auth_router prefix, forwarded to :meth:oauth_redirect_uri. Defaults to "/auth".

'/auth'

Returns:

Name Type Description
GitHubOAuthKwargs GitHubOAuthKwargs

client_id, client_secret and the

GitHubOAuthKwargs

derived redirect_uri. Scopes are left to the client's

GitHubOAuthKwargs

own defaults (read:user user:email).

StorageSettings

Bases: BaseAppSettings

S3-compatible object storage configuration.

Consumed by :class:tempest_fastapi_sdk.AsyncMinIOClient, which speaks the S3 API to any compatible target (AWS S3, MinIO, Backblaze B2, Cloudflare R2, Wasabi, DigitalOcean Spaces) — the MinIO in the client's name is the library it uses, not a requirement on the server.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix). Every field that used to be MINIO_* (when this mixin was MinIOSettings) still reads the old name as a fallback through :attr:DEPRECATED_ENV_ALIASES and :class:~tempest_fastapi_sdk.settings.DeprecatedEnvAliasesSettingsSource. Setting both names of a pair to different values refuses to build — see :func:~tempest_fastapi_sdk.settings.reject_conflicting_env_aliases — and reading from a MINIO_* variable emits a DeprecationWarning and a structured boot log naming the replacement.

The defaults are a local MinIO's (minioadmin/minioadmin over plain HTTP). In ENV=production (see :class:EnvironmentSettings) those keys, STORAGE_SECURE=False and an explicit STORAGE_PUBLIC_SECURE=False are refused — except that STORAGE_SECURE=False is accepted for the split-endpoint shape described in :meth:private_plain_http_allowed (a private bucket behind an HTTPS public endpoint).

Attributes:

Name Type Description
STORAGE_ENDPOINT str

host[:port] without scheme. Old name MINIO_ENDPOINT. Default: "localhost:9000".

STORAGE_ACCESS_KEY str

S3 access key / IAM user. Old name MINIO_ACCESS_KEY. Default: "minioadmin".

STORAGE_SECRET_KEY str

S3 secret key. Old name MINIO_SECRET_KEY. Default: "minioadmin".

STORAGE_SECURE bool

Use HTTPS when True. Old name MINIO_SECURE. Default: False.

STORAGE_REGION str

S3 region. Old name MINIO_REGION. Default: "us-east-1".

STORAGE_DEFAULT_BUCKET str

Bucket ensured and used as the implicit target. Old name MINIO_DEFAULT_BUCKET. Default: "uploads".

STORAGE_PUBLIC_ENDPOINT str | None

Public host presigned URLs are signed against, when the browser can't reach STORAGE_ENDPOINT directly. None reuses STORAGE_ENDPOINT. Old name MINIO_PUBLIC_ENDPOINT. Default: None.

STORAGE_PUBLIC_SECURE bool | None

HTTPS for the public endpoint; None falls back to STORAGE_SECURE. Old name MINIO_PUBLIC_SECURE. Default: None.

STORAGE_ACCEL_REDIRECT bool

True makes AsyncMinIOClient.serve_object answer with X-Accel-Redirect for nginx instead of proxying the bytes. Default: False.

STORAGE_ACCEL_PREFIX str

nginx internal location the X-Accel-Redirect points into. Default: "/_bucket/".

STORAGE_ENABLED bool

Kill-switch for the whole integration. False skips the production checks above, lists "storage" in :meth:disabled_integrations and makes :meth:storage_kwargs build an AsyncMinIOClient whose every operation raises IntegrationDisabledException (503). Default: True.

STORAGE_BACKEND Literal['s3', 'local']

Where objects live. "s3" (default) is an S3-compatible store through :class:AsyncMinIOClient; "local" is a directory of the server through :class:LocalObjectStorageClient, with links signed to the app's own routes. :meth:build_storage_client picks the client from it.

STORAGE_LOCAL_DIR str

Root directory of the local store. Default: "var/storage" (relative to the working directory; production requires an absolute path).

STORAGE_LOCAL_PUBLIC_URL str

Scheme and host the browser reaches the app at; local links start with it. Default: "http://127.0.0.1:8000".

STORAGE_LOCAL_ROUTE_PREFIX str

Path the signed local routes are mounted at, as the app sees it. Default: "/storage".

STORAGE_LOCAL_SIGNING_SECRET str

Secret the local links are signed with. Default: a development placeholder, refused in production.

STORAGE_LOCAL_MAX_UPLOAD_BYTES int

Largest body the signed local PUT accepts. Default: 25 MiB.

STORAGE_LOCAL_ENCRYPTION_KEYS dict[str, str]

Key id to base64 of a 32-byte AES-256 key, as JSON. Set, the local store encrypts every object at rest with the first key and reads with any. Default: {} (plaintext). Needs the [storage-encryption] extra.

STORAGE_LOCAL_ALLOW_PLAINTEXT_READ bool

With keys, serve a file written before encryption as plaintext until it is migrated. Default: False.

STORAGE_BUCKET_CREDENTIALS dict[str, StorageBucketCredential]

Bucket name to {"access_key": ..., "secret_key": ...}, as JSON, for a store that binds each key to one bucket. Set, :meth:build_storage_client returns a :class:~tempest_fastapi_sdk.storage.BucketRoutedMinIOClient that signs each call with the credential of the bucket it names, and STORAGE_ACCESS_KEY / STORAGE_SECRET_KEY answer every other bucket. A credential missing either key, or with an empty one, refuses to build. The secrets are SecretStr. Default: {}.

decode_local_encryption_keys staticmethod

decode_local_encryption_keys(value: Mapping[str, str]) -> dict[str, bytes]

Decode the base64 keys of STORAGE_LOCAL_ENCRYPTION_KEYS.

Parameters:

Name Type Description Default
value Mapping[str, str]

Key id to base64 key.

required

Returns:

Type Description
dict[str, bytes]

dict[str, bytes]: Key id to raw key, in the same order.

Raises:

Type Description
ValueError

When a value is not valid base64; the message names the key id only.

local_storage_kwargs

local_storage_kwargs() -> LocalStorageKwargs

Map these settings onto :class:LocalObjectStorageClient kwargs.

With STORAGE_ENABLED off the dictionary carries enabled=False, as :meth:storage_kwargs does for S3. With STORAGE_LOCAL_ENCRYPTION_KEYS set it carries the decoded encryption_keys and allow_plaintext_read; without keys neither key is present, so the dictionary is the one it always was.

Returns:

Name Type Description
LocalStorageKwargs LocalStorageKwargs

Keyword arguments ready to splat into

LocalStorageKwargs

LocalObjectStorageClient(**settings.local_storage_kwargs()).

build_storage_client

build_storage_client() -> AsyncMinIOClient | LocalObjectStorageClient

Build the object-storage client STORAGE_BACKEND names.

Both clients satisfy :class:~tempest_fastapi_sdk.privacy.SubjectStorageClient, so the rest of the service does not care which one it got. With local, mount :func:~tempest_fastapi_sdk.storage.make_local_storage_router so the links it signs have a route to land on.

With s3 and STORAGE_BUCKET_CREDENTIALS set, the client is a :class:~tempest_fastapi_sdk.storage.BucketRoutedMinIOClient — a subclass of :class:AsyncMinIOClient, so the annotation and every call site stay the same — that signs each bucket with its own key.

Returns:

Name Type Description
AsyncMinIOClient | LocalObjectStorageClient

AsyncMinIOClient | LocalObjectStorageClient: The client, built

from AsyncMinIOClient | LocalObjectStorageClient

meth:storage_kwargs or :meth:local_storage_kwargs.

Raises:

Type Description
ImportError

For s3 without the [minio] extra.

storage_kwargs

storage_kwargs() -> StorageKwargs

Map these settings onto :class:AsyncMinIOClient kwargs.

With STORAGE_ENABLED off the dictionary also carries enabled=False, so the same construction line builds a client that refuses every operation with IntegrationDisabledException instead of reaching the development endpoint. The key is absent while the integration is on, so the dictionary of a deployment that never touches the flag is unchanged.

Returns:

Name Type Description
StorageKwargs StorageKwargs

Keyword arguments ready to splat into

StorageKwargs

AsyncMinIOClient(**settings.storage_kwargs()).

minio_kwargs

minio_kwargs() -> StorageKwargs

Return :meth:storage_kwargs under its pre-rename name.

Kept so code written against MinIOSettings keeps working after composing :class:StorageSettings; the output is the same dictionary.

Returns:

Name Type Description
StorageKwargs StorageKwargs

Same as :meth:storage_kwargs.

production_violations

production_violations() -> list[str]

Refuse the local MinIO credentials and plain HTTP in production.

The defaults compared against are read from StorageSettings.model_fields, so they follow the declared default instead of a copied literal. STORAGE_PUBLIC_SECURE is only refused when explicitly False: None inherits STORAGE_SECURE, which is checked on its own.

Skipped entirely when STORAGE_ENABLED is off. With STORAGE_BACKEND=local the S3 fields are not checked — nothing reads them — and :meth:local_storage_violations runs instead.

Each STORAGE_BUCKET_CREDENTIALS entry whose secret is still the MinIO default is refused like STORAGE_SECRET_KEY; with STORAGE_BACKEND=local a non-empty STORAGE_BUCKET_CREDENTIALS is refused, because nothing would read it.

A local store without STORAGE_LOCAL_ENCRYPTION_KEYS is not a violation: refusing it would stop, on upgrade and without notice, every service that already runs the local backend in production. It logs a WARNING on the tempest_fastapi_sdk.settings logger instead, each time the production guard runs.

Returns:

Type Description
list[str]

list[str]: The parent's entries plus one per offending field.

local_storage_violations

local_storage_violations() -> list[str]

List what the local backend cannot ship to production with.

  • STORAGE_LOCAL_SIGNING_SECRET still the development placeholder (anyone could forge a link) or empty;
  • STORAGE_LOCAL_PUBLIC_URL not https (the signed link travels in the clear);
  • STORAGE_LOCAL_DIR relative (it would follow the working directory, which differs between the API and the worker).

Returns:

Type Description
list[str]

list[str]: One entry per offending field; empty when none.

is_private_endpoint staticmethod

is_private_endpoint(endpoint: str) -> bool

Tell whether a host[:port] endpoint is reachable only privately.

Private means a single-label hostname (a Docker service name such as bucket, or localhost), or an IP in :data:_PRIVATE_STORAGE_NETWORKS (RFC 1918, loopback, link-local, IPv6 ULA). A scheme and a path, if present, are ignored; an IPv6 address may come bracketed ([fd00::1]:9000).

Parameters:

Name Type Description Default
endpoint str

The endpoint, as STORAGE_ENDPOINT holds it.

required

Returns:

Name Type Description
bool bool

True for a private host, False for anything with

bool

a dot that is not a private IP (a public DNS name).

private_plain_http_allowed

private_plain_http_allowed() -> bool

Whether STORAGE_SECURE=False is the split-endpoint shape.

Plain HTTP between the app and the bucket is a legitimate production setup when the bucket is only reachable on a private network (STORAGE_ENDPOINT=bucket:9000 inside a compose network) and clients only ever see presigned URLs signed for an HTTPS public host. All three must hold:

  • STORAGE_ENDPOINT is private (:meth:is_private_endpoint);
  • STORAGE_PUBLIC_ENDPOINT is set;
  • the public scheme is HTTPS — STORAGE_PUBLIC_SECURE=True, or None with an https:// public endpoint (what AsyncMinIOClient resolves the same way).

Returns:

Name Type Description
bool bool

True when plain HTTP is confined to the private hop.

disabled_integrations

disabled_integrations() -> list[str]

Append "storage" when STORAGE_ENABLED is off.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus "storage" when off.

MinIOSettings

Bases: StorageSettings

Deprecated name of :class:StorageSettings.

Composing it (or instantiating it directly) emits a DeprecationWarning; switch the base to :class:StorageSettings. The environment variables need no change — MINIO_* keeps working on both classes — and the MINIO_* attributes below keep code that reads settings.MINIO_ENDPOINT working until it moves to the STORAGE_* attributes.

MINIO_ENDPOINT property

MINIO_ENDPOINT: str

Deprecated read of :attr:StorageSettings.STORAGE_ENDPOINT.

Returns:

Name Type Description
str str

The storage endpoint.

MINIO_ACCESS_KEY property

MINIO_ACCESS_KEY: str

Deprecated read of :attr:StorageSettings.STORAGE_ACCESS_KEY.

Returns:

Name Type Description
str str

The access key.

MINIO_SECRET_KEY property

MINIO_SECRET_KEY: str

Deprecated read of :attr:StorageSettings.STORAGE_SECRET_KEY.

Returns:

Name Type Description
str str

The secret key.

MINIO_SECURE property

MINIO_SECURE: bool

Deprecated read of :attr:StorageSettings.STORAGE_SECURE.

Returns:

Name Type Description
bool bool

Whether the endpoint uses HTTPS.

MINIO_REGION property

MINIO_REGION: str

Deprecated read of :attr:StorageSettings.STORAGE_REGION.

Returns:

Name Type Description
str str

The S3 region.

MINIO_DEFAULT_BUCKET property

MINIO_DEFAULT_BUCKET: str

Deprecated read of :attr:StorageSettings.STORAGE_DEFAULT_BUCKET.

Returns:

Name Type Description
str str

The default bucket.

MINIO_PUBLIC_ENDPOINT property

MINIO_PUBLIC_ENDPOINT: str | None

Deprecated read of :attr:StorageSettings.STORAGE_PUBLIC_ENDPOINT.

Returns:

Type Description
str | None

str | None: The public endpoint, or None.

MINIO_PUBLIC_SECURE property

MINIO_PUBLIC_SECURE: bool | None

Deprecated read of :attr:StorageSettings.STORAGE_PUBLIC_SECURE.

Returns:

Type Description
bool | None

bool | None: HTTPS for the public endpoint, or None.

model_post_init

model_post_init(context: object) -> None

Warn when MinIOSettings itself is instantiated.

Parameters:

Name Type Description Default
context object

Pydantic's post-init context, forwarded.

required

SessionCookieDeleteKwargs

Bases: TypedDict

Keyword arguments for Response.delete_cookie on the session cookie.

Returned by :meth:SessionSettings.session_cookie_delete_kwargs.

Attributes:

Name Type Description
key str

Cookie name (SESSION_COOKIE_NAME).

path str

Cookie Path (SESSION_COOKIE_PATH).

domain str | None

Cookie Domain (SESSION_COOKIE_DOMAIN).

secure bool

Secure flag (SESSION_COOKIE_SECURE).

httponly bool

HttpOnly flag (SESSION_COOKIE_HTTPONLY).

samesite SessionCookieSameSite

SameSite policy (SESSION_COOKIE_SAMESITE).

SessionCookieKwargs

Bases: SessionCookieDeleteKwargs

Keyword arguments for Response.set_cookie on the session cookie.

Returned by :meth:SessionSettings.session_cookie_kwargs: every key of :class:SessionCookieDeleteKwargs plus the lifetime.

Attributes:

Name Type Description
max_age int

Cookie Max-Age in seconds (SESSION_TTL_SECONDS).

SessionSettings

Bases: BaseAppSettings

Server-side session cookie + storage configuration.

Consumed by :class:tempest_fastapi_sdk.SessionAuth, :class:tempest_fastapi_sdk.SessionMiddleware, and :func:tempest_fastapi_sdk.make_session_router. Defaults assume HTTPS in production (SESSION_COOKIE_SECURE=True) and a same-site SaaS topology (SESSION_COOKIE_SAMESITE="lax") — relax both only for local HTTP development.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
SESSION_TTL_SECONDS int

Lifetime of a server-side session. Default: 86400.

SESSION_SLIDING bool

Refresh expires_at on every request. Default: True.

SESSION_COOKIE_NAME str

Name of the session cookie. Default: "tempest_session".

SESSION_COOKIE_DOMAIN str | None

Cookie Domain attribute; None scopes to the issuing host. Default: None.

SESSION_COOKIE_PATH str

Cookie Path attribute. Default: "/".

SESSION_COOKIE_SECURE bool

Send the cookie only over HTTPS. Default: True.

SESSION_COOKIE_HTTPONLY bool

Hide the cookie from page JavaScript. Default: True.

SESSION_COOKIE_SAMESITE SessionCookieSameSite

Cookie SameSite policy (lax/strict/none, lowercase; surrounding whitespace is trimmed, anything else fails at construction). Default: "lax".

SESSION_ROTATE_ON_LOGIN bool

Issue a new session id on login. Default: True.

Examples:

Write and clear the cookie with the two mappers instead of repeating the settings at each call site::

response.set_cookie(value=token, **settings.session_cookie_kwargs())
response.delete_cookie(**settings.session_cookie_delete_kwargs())
session_cookie_kwargs() -> SessionCookieKwargs

Map these settings onto Response.set_cookie keyword arguments.

Carries the cookie name as key, so the call site passes only the session id::

response.set_cookie(value=plaintext, **settings.session_cookie_kwargs())

max_age tracks SESSION_TTL_SECONDS, the same lifetime the store gives the session.

Returns:

Name Type Description
SessionCookieKwargs SessionCookieKwargs

key, max_age, path,

SessionCookieKwargs

domain, secure, httponly and samesite, typed

SessionCookieKwargs

so mypy checks the splat against Starlette's signature.

session_cookie_delete_kwargs() -> SessionCookieDeleteKwargs

Map these settings onto Response.delete_cookie keyword arguments.

A browser only drops a cookie when the deleting Set-Cookie names the same path and domain it was set with, so both come from the same fields :meth:session_cookie_kwargs reads, together with the Secure / HttpOnly / SameSite attributes::

response.delete_cookie(**settings.session_cookie_delete_kwargs())

Returns:

Name Type Description
SessionCookieDeleteKwargs SessionCookieDeleteKwargs

key, path, domain,

SessionCookieDeleteKwargs

secure, httponly and samesite.

WebSocketSettings

Bases: BaseAppSettings

WebSocket router configuration.

Consumed by :func:tempest_fastapi_sdk.make_websocket_router and :class:tempest_fastapi_sdk.WebSocketHub. Defaults are tuned for typical browser ↔ FastAPI deployments — heartbeats every 30s, drop after 60s without pong, five concurrent connections per user.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
WS_HEARTBEAT_SECONDS int

How often the server sends a ping frame. Default: 30.

WS_HEARTBEAT_TIMEOUT_SECONDS int

Max ping-to-pong delay before force-close. Default: 60.

WS_MAX_CONNECTIONS_PER_USER int

Cap on concurrent connections per user. Default: 5.

WS_MAX_MESSAGE_BYTES int

Reject inbound frames larger than this. Default: 65536.

GenAISettings

Bases: BaseAppSettings

Where model weights live, and whether loads may use the network.

The genai loaders read these three variables as defaults: an argument passed to a loader always wins, so a service pins the cache and the offline switch once — compose, chart, systemd unit — and a call that needs something different still says so per model.

from tempest_fastapi_sdk import BaseAppSettings, GenAISettings


class Settings(GenAISettings, BaseAppSettings):
    pass
# .env — read by the loaders even without the class above
GENAI_CACHE_DIR=/models      # survives a container restart
GENAI_OFFLINE=true           # never reach the Hub at load time
GENAI_HF_TOKEN=hf_xxx        # gated repos, and no anonymous rate limit

Declaring the class is what makes the values typed, documented and visible in tempest check-config; the loaders themselves read the environment directly, so a service that never declares it still gets the same behaviour.

Attributes:

Name Type Description
GENAI_CACHE_DIR str | None

Weight cache directory. None keeps the huggingface_hub default ($HF_HOME/hub, else ~/.cache/huggingface/hub). Default: None.

GENAI_OFFLINE bool

Load from that cache without touching the network. Default: False.

GENAI_HF_TOKEN str | None

Hub token for gated or private repositories. Default: None.

HostedGenAISettings

Bases: BaseAppSettings

Keys, endpoints and models of the hosted generation providers.

Kept apart from :class:GenAISettings, which is about local weights: a service that only calls a hosted API has no cache directory to declare, and one that runs both composes the two.

Each *_kwargs() returns what the matching backend's constructor takes, so building it is a splat::

AnthropicGenerator(**settings.anthropic_kwargs())
OpenAICompatGenerator(**settings.openai_kwargs())
OpenAICompatGenerator(**settings.deepseek_kwargs())
OpenAICompatGenerator(**settings.gemini_kwargs())
OpenAICompatSpeech(**settings.openai_speech_kwargs())

And :meth:hosted_kwargs picks the provider from the model id, for a service that should change provider by changing one model variable::

hosted_generator(**settings.hosted_kwargs("claude-haiku-5-5"))

A service that wants the provider, the key and the API root stated explicitly — one provider for every model it calls, chosen in .env rather than inferred from a model id — sets GENAI_PROVIDER, GENAI_API_KEY and, optionally, GENAI_BASE_URL. With GENAI_PROVIDER set, :meth:hosted_kwargs uses that provider for every model, takes GENAI_API_KEY (falling back to the provider's own *_API_KEY) and GENAI_BASE_URL (falling back to the provider's own *_BASE_URL), and refuses a model id whose prefix names a different provider instead of switching silently. Unset, nothing changes: the provider still comes from the model id.

The mapping is also where the per-provider wire differences live: the OpenAI kwargs send max_new_tokens as max_completion_tokens (the OpenAI spec marks max_tokens deprecated) and ask for JSON with json_schema; the DeepSeek kwargs keep max_tokens and use json_object, the only JSON mode DeepSeek documents (https://api-docs.deepseek.com/guides/json_mode).

An empty key is not rejected here — a service may configure one provider and not the others — but the backend constructor raises ValueError on it, and :meth:openai_kwargs raises when OPENAI_MODEL is unset (:meth:openai_speech_kwargs when OPENAI_STT_MODEL is).

Each attribute is also the name of the environment variable that sets it (case-sensitive, no prefix).

Attributes:

Name Type Description
ANTHROPIC_API_KEY str

Anthropic API key. Default: "".

ANTHROPIC_BASE_URL str

API root; /v1/messages is appended. Default: "https://api.anthropic.com".

ANTHROPIC_MODEL str

Model id. Default: "claude-opus-5-5".

OPENAI_API_KEY str

OpenAI API key. Default: "".

OPENAI_BASE_URL str

API root; /chat/completions is appended. Default: "https://api.openai.com/v1".

OPENAI_MODEL str

Model id. No default: OpenAI model ids are not hard-coded in this SDK. Default: "".

OPENAI_STT_MODEL str

Transcription model id for OpenAICompatSpeech, sent to the same OPENAI_BASE_URL with the same OPENAI_API_KEY. No default. Default: "".

DEEPSEEK_API_KEY str

DeepSeek API key. Default: "".

DEEPSEEK_BASE_URL str

API root. Default: "https://api.deepseek.com".

DEEPSEEK_MODEL str

Model id. Default: "deepseek-flash".

GOOGLE_API_KEY str

Gemini API key. Default: "".

GOOGLE_BASE_URL str

Gemini's OpenAI-compatible API root; /chat/completions is appended. Default: "https://generativelanguage.googleapis.com/v1beta/openai".

GOOGLE_MODEL str

Model id. No default: Gemini model ids are not hard-coded in this SDK. Default: "".

GENAI_PROVIDER Literal['anthropic', 'openai', 'google', 'deepseek'] | None

The one provider every model goes to. None (or empty in .env) keeps resolving the provider from each model id. Default: None.

GENAI_API_KEY str

Key for GENAI_PROVIDER; empty falls back to that provider's *_API_KEY. Default: "".

GENAI_BASE_URL str

API root for GENAI_PROVIDER; empty falls back to that provider's *_BASE_URL. Default: "".

genai_effective_api_key

genai_effective_api_key() -> str

The key GENAI_PROVIDER will be called with.

Returns:

Name Type Description
str str

GENAI_API_KEY, or the provider's own *_API_KEY when

str

it is empty; "" when GENAI_PROVIDER is unset.

production_violations

production_violations() -> list[str]

Refuse a chosen provider with no key to call it.

A service that never sets GENAI_PROVIDER is not affected: the per-provider keys may stay empty for the providers it does not use.

Returns:

Type Description
list[str]

list[str]: The parent's entries plus one when GENAI_PROVIDER

list[str]

is set and neither GENAI_API_KEY nor the provider's own

list[str]

*_API_KEY holds a key.

anthropic_kwargs

anthropic_kwargs() -> AnthropicKwargs

Map these settings onto AnthropicGenerator.

Returns:

Name Type Description
AnthropicKwargs AnthropicKwargs

model, api_key and base_url.

openai_kwargs

openai_kwargs() -> OpenAIKwargs

Map these settings onto OpenAICompatGenerator for OpenAI.

Returns:

Name Type Description
OpenAIKwargs OpenAIKwargs

model, api_key, base_url,

OpenAIKwargs

provider="openai", max_tokens_field="max_completion_tokens"

OpenAIKwargs

and structured_output="json_schema".

Raises:

Type Description
ValueError

When OPENAI_MODEL is empty.

openai_speech_kwargs

openai_speech_kwargs() -> OpenAISpeechKwargs

Map these settings onto OpenAICompatSpeech.

The key and the API root are the ones :meth:openai_kwargs uses (OPENAI_API_KEY, OPENAI_BASE_URL); only the model differs, because a server serves one transcription model and one chat model under different ids.

Returns:

Name Type Description
OpenAISpeechKwargs OpenAISpeechKwargs

model (OPENAI_STT_MODEL), api_key,

OpenAISpeechKwargs

base_url and provider="openai".

Raises:

Type Description
ValueError

When OPENAI_STT_MODEL is empty.

deepseek_kwargs

deepseek_kwargs() -> DeepSeekKwargs

Map these settings onto OpenAICompatGenerator for DeepSeek.

Returns:

Name Type Description
DeepSeekKwargs DeepSeekKwargs

model, api_key, base_url,

DeepSeekKwargs

provider="deepseek", structured_output="json_object" and

DeepSeekKwargs

effort_field=None (DeepSeek does not document

DeepSeekKwargs

reasoning_effort, so effort is not sent, as with

DeepSeekKwargs

hosted_generator) and accepts_documents=False (no PDF

DeepSeekKwargs

input documented, see genai.supports_documents).

gemini_kwargs

gemini_kwargs() -> GeminiKwargs

Map these settings onto OpenAICompatGenerator for Gemini.

Returns:

Name Type Description
GeminiKwargs GeminiKwargs

model, api_key, base_url,

GeminiKwargs

provider="google", structured_output="json_schema",

GeminiKwargs

effort_values=GOOGLE_EFFORT_VALUES and

GeminiKwargs

accepts_documents=False (no PDF input documented on the

GeminiKwargs

OpenAI-compatible endpoint, see genai.supports_documents).

Raises:

Type Description
ValueError

When GOOGLE_MODEL is empty.

hosted_kwargs

hosted_kwargs(model: str, *, provider: str | None = None) -> HostedGenAIKwargs

Map these settings onto hosted_generator for model.

Without GENAI_PROVIDER, the provider comes from provider or, when None, from the model id (genai.resolve_provider); the key and the API root are that provider's fields here.

With GENAI_PROVIDER set, that provider takes every model: the key is GENAI_API_KEY (or the provider's own *_API_KEY when empty) and the API root is GENAI_BASE_URL (or the provider's own *_BASE_URL). A model id whose prefix names another provider, or a provider argument that disagrees, raises instead of switching silently; an id with no known prefix (a fine-tune, a model behind an OpenAI-compatible server) goes to GENAI_PROVIDER.

An empty key is returned as is — the generator constructor raises on it, as with the other *_kwargs.

Parameters:

Name Type Description Default
model str

The model id to call.

required
provider str | None

The provider, when the model id does not say it ("anthropic", "openai", "google", "deepseek").

None

Returns:

Name Type Description
HostedGenAIKwargs HostedGenAIKwargs

model, api_key, base_url and

HostedGenAIKwargs

provider — the keyword arguments of hosted_generator.

Raises:

Type Description
ValueError

When the provider cannot be resolved from model, provider names one this mixin has no fields for, or model/provider disagree with GENAI_PROVIDER.

OpenPixSettings

Bases: BaseAppSettings

OpenPix / Woovi credentials and environment.

Every other integration with a credential ships a mixin like this one; OpenPix did not, so a service repeated the AppID field and the base-URL lookup by hand. :meth:openpix_kwargs closes that, and it also hides the one thing about this API that is easy to get wrong: the AppID travels in Authorization raw, with no Bearer prefix.

The environment is a string here rather than :class:~tempest_fastapi_sdk.integrations.payment.openpix.OpenPixEnvironmentEnum on purpose: settings must not pull the integrations namespace, which is lazy so import tempest_fastapi_sdk never pays for 373 generated names. :meth:openpix_kwargs imports the enum when it runs, so the base URL still has a single source of truth.

Deliberately no enabled property, unlike the push mixins: three of them already define one, and a service that takes Pix and sends push would inherit a collision. Check bool(settings.OPENPIX_APP_ID) instead.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
OPENPIX_APP_ID str

The AppID issued by OpenPix/Woovi, sent raw in Authorization. Default: "" (calls will be rejected).

OPENPIX_ENVIRONMENT Literal['production', 'sandbox']

Which API to talk to. Default: "sandbox" — pointing at production by accident charges real money, while pointing at sandbox by accident fails loudly.

openpix_kwargs

openpix_kwargs() -> HTTPClientKwargs

Map these settings onto the HTTPClient the client wraps.

:class:~tempest_fastapi_sdk.integrations.payment.openpix.OpenPixClient takes an already-configured HTTPClient and reads its credentials from default_headers, so this returns what that client needs::

client = OpenPixClient(HTTPClient(**settings.openpix_kwargs()))

Returns:

Name Type Description
HTTPClientKwargs HTTPClientKwargs

base_url resolved from the environment, plus

HTTPClientKwargs

the Authorization header carrying the AppID.

MercadoPagoSettings

Bases: BaseAppSettings

Mercado Pago credentials.

Two secrets with different jobs: the access token authenticates you to Mercado Pago, and the webhook secret authenticates them to you. Both are here because a service that charges needs both, and leaving the second one to be improvised is how an unverified webhook endpoint ships.

Deliberately no environment field, unlike :class:OpenPixSettings. Measured on the pinned specification: Mercado Pago declares a single server, https://api.mercadopago.com, so what separates a test charge from a real one is which token you hold. An environment enum here would suggest a safety net that does not exist — and would let someone believe a "sandbox" setting protects them while a production token moves real money.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
MERCADOPAGO_ACCESS_TOKEN str

The access token, sent as Authorization: Bearer <token>. Default: "" (calls will be rejected).

MERCADOPAGO_WEBHOOK_SECRET str

The secret that signs incoming notifications. Default: "" — and an empty secret makes verify_signature return False for everything, rather than accepting everything.

MERCADOPAGO_BASE_URL str

The host :meth:mercado_pago_kwargs points the client at. Default: DEFAULT_BASE_URL (https://api.mercadopago.com). Change it only to aim a development service at the simulator (tempest mercado-pago fake-api); anything else in production is reported by :meth:production_violations, because the access token travels to whatever host this names.

production_violations

production_violations() -> list[str]

Refuse a Mercado Pago host other than the provider's in production.

Returns:

Type Description
list[str]

list[str]: The parent's entries plus one when

list[str]

MERCADOPAGO_BASE_URL is not DEFAULT_BASE_URL — the

list[str]

access token is sent to that host on every call.

mercado_pago_kwargs

mercado_pago_kwargs() -> HTTPClientKwargs

Map these settings onto the HTTPClient the client wraps.

Returns:

Name Type Description
HTTPClientKwargs HTTPClientKwargs

base_url and the Authorization header,

HTTPClientKwargs

ready for::

client = MercadoPagoClient( HTTPClient(**settings.mercado_pago_kwargs()) )

Note the Bearer prefix — the opposite of OpenPix, which takes its AppID raw. Getting that backwards is a 401 on every call, and it is exactly the kind of thing this method exists to settle once.

An empty MERCADOPAGO_ACCESS_TOKEN sends no Authorization header at all: Bearer with nothing after it is an illegal header value that httpx refuses before sending (httpx.LocalProtocolError), which made a development service pointed at tempest mercado-pago fake-api fail on every call until it set a placeholder token the fake-api never reads.

RevenueCatSettings

Bases: BaseAppSettings

RevenueCat credentials: two webhook secrets and one API key.

The webhook secrets authenticate RevenueCat to you; the API key authenticates you to RevenueCat, for the reconciliation read. All three are documented on https://www.revenuecat.com/docs/integrations/webhooks and https://www.revenuecat.com/docs/api-v1.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
REVENUECAT_WEBHOOK_SECRET str

The Authorization header value typed in the dashboard's webhook integration. Default "". Empty means the header is not checked; with the signing secret empty too, the webhook refuses every delivery rather than accept every one.

REVENUECAT_WEBHOOK_SIGNING_SECRET str

The HMAC signing secret, when "HMAC webhook signing" is enabled on the integration. Empty means signing is not checked; with REVENUECAT_WEBHOOK_SECRET empty too, every delivery is refused.

REVENUECAT_API_KEY str

A secret API key (sk_...) for GET /v1/subscribers. Empty disables reconciliation.

REVENUECAT_ENABLED bool

Kill-switch for the whole integration. False skips the production check below and lists "revenuecat" in :meth:disabled_integrations. Nothing else changes: the webhook dependency reads its secrets, not this flag, so with both secrets empty it keeps refusing every delivery with 401. Default: True.

revenuecat_kwargs

revenuecat_kwargs() -> HTTPClientKwargs

Map these settings onto the HTTPClient the client wraps.

Returns:

Name Type Description
HTTPClientKwargs HTTPClientKwargs

base_url and the Authorization header,

HTTPClientKwargs

ready for::

client = RevenueCatClient(HTTPClient(**settings.revenuecat_kwargs()))

production_violations

production_violations() -> list[str]

Refuse a production boot that would reject every webhook.

With both webhook secrets empty the endpoint refuses everything — safe, but in production it means every purchase, renewal and expiration is answered 401 and dropped after RevenueCat's last retry. That is an outage, so it fails the boot. Either secret alone is a configured service: the webhook dependency checks each filled secret and skips an empty one, so HMAC alone (or the header alone) authenticates.

Skipped entirely when REVENUECAT_ENABLED is off.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus one when neither webhook

list[str]

secret is set.

disabled_integrations

disabled_integrations() -> list[str]

Append "revenuecat" when REVENUECAT_ENABLED is off.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus "revenuecat" when off.

HostBridgeSettings

Bases: BaseAppSettings

Host control configuration, consumed by HostBridge.

Compose it into a service's settings and splat :meth:hostbridge_kwargs into :class:~tempest_fastapi_sdk.hostbridge.HostBridgeConfig.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

HOST_ALLOWED_BASE_PATHS has no permissive default on purpose. The surface it guards reads the host's disk and, with the write side enabled, runs commands as the host user — a bridge that allows everything because nobody configured it is the failure worth designing against. Empty denies every path.

Attributes:

Name Type Description
HOST_ALLOWED_BASE_PATHS list[str]

Directories the file surface may reach. Default: [], which denies everything.

HOST_POWERSHELL_BINARY str

PowerShell executable. Default: "powershell.exe".

HOST_CMD_BINARY str

cmd executable. Default: "cmd.exe".

HOST_COMMAND_TIMEOUT int

Seconds a command may run when the caller names no timeout. Default: 30.

HOST_MAX_FILE_READ_BYTES int

Ceiling for a single read. Default: 10485760 (10 MiB).

HOST_BRIDGE_URL str

Origin of a host agent (tempest hostbridge serve) to forward every call to. Default: "" — act on this machine instead.

HOST_BRIDGE_TOKEN SecretStr

Shared secret the agent checks. The agent reads the same variable, so one value configures both sides. Required when HOST_BRIDGE_URL is set.

hostbridge_kwargs

hostbridge_kwargs() -> HostBridgeKwargs

Map these settings onto :class:HostBridgeConfig kwargs.

Returns:

Name Type Description
HostBridgeKwargs HostBridgeKwargs

Keyword arguments ready to splat into

HostBridgeKwargs

HostBridgeConfig(**settings.hostbridge_kwargs()).

remote_hostbridge_kwargs

remote_hostbridge_kwargs() -> RemoteHostBridgeKwargs

Map these settings onto :class:RemoteHostBridge kwargs.

Returns:

Name Type Description
RemoteHostBridgeKwargs RemoteHostBridgeKwargs

Keyword arguments ready to splat into

RemoteHostBridgeKwargs

RemoteHostBridge(**settings.remote_hostbridge_kwargs()).

is_reserved_domain

is_reserved_domain(domain: str) -> bool

Tell whether a DNS name can never be a real public host.

True for example.com, example.net, example.org and localhost (and their subdomains), and for anything under the reserved top-level domains .example, .invalid, .localhost and .test (RFC 2606 / RFC 6761). Shared by the SMTP_FROM_ADDR rule of :class:EmailSettings and the e-mail link rule of :class:AuthSettings.

Parameters:

Name Type Description Default
domain str

The host name, any case; a trailing dot is ignored.

required

Returns:

Name Type Description
bool bool

True for a reserved name.

email_link_violation(field: str, template: str) -> str | None

Judge one e-mail link template for a production deployment.

The link is read by a real person on another machine, and the token travels in the URL, so two things are refused: a scheme other than https (http:// exposes the token on the wire), and a host nobody else can reach — empty, localhost, a loopback or unspecified IP (127.0.0.1, ::1, 0.0.0.0), or a reserved name (:func:is_reserved_domain). The {token} placeholder is replaced before parsing.

Parameters:

Name Type Description Default
field str

The settings field name, used in the message.

required
template str

The configured URL template.

required

Returns:

Type Description
str | None

str | None: A "FIELD: reason" entry naming the field and never

str | None

the value, or None when the template is acceptable.

GmapsScraperSettings

Bases: BaseAppSettings

Connection and job-polling settings for the Google Maps scraper sidecar.

Opt-in by default (GMAPS_SCRAPER_ENABLED=False) because the scraper runs as an optional sidecar container. When enabled in production, :meth:production_violations refuses an empty GMAPS_SCRAPER_URL.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
GMAPS_SCRAPER_ENABLED bool

Opt-in switch for the scraper sidecar. False skips the production URL check and appends "gmaps_scraper" to :meth:disabled_integrations. Default: False.

GMAPS_SCRAPER_URL str

Internal base URL of the sidecar (for example "http://gmaps-scraper:8080"). Default: "".

GMAPS_SCRAPER_TIMEOUT float

Per-request HTTP timeout in seconds. Must be strictly positive. Default: 30.0.

GMAPS_SCRAPER_POLL_SECONDS float

Delay between job status polls in seconds. Must be strictly positive. Default: 2.0.

GMAPS_SCRAPER_WAIT_SECONDS float

Maximum total time to wait for a scraping job to finish before raising :class:~tempest_fastapi_sdk.exceptions.GmapsScraperJobError. Must be strictly positive. Default: 600.0.

GMAPS_SCRAPER_MAX_TIME_SECONDS int

Server-side max_time budget sent to the scraper in nanoseconds. gosom/google-maps-scraper rejects values under 180 seconds. Default: 180.

production_violations

production_violations() -> list[str]

Refuse an enabled scraper without a sidecar URL in production.

Skipped entirely when GMAPS_SCRAPER_ENABLED is False.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus one when

list[str]

GMAPS_SCRAPER_ENABLED is True and GMAPS_SCRAPER_URL is

list[str]

empty.

disabled_integrations

disabled_integrations() -> list[str]

Append "gmaps_scraper" when GMAPS_SCRAPER_ENABLED is off.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus "gmaps_scraper" when

list[str]

disabled.

gmaps_scraper_http_kwargs

gmaps_scraper_http_kwargs() -> GmapsScraperHTTPKwargs

Map these settings onto gmaps_scraper_http_client.

Use as::

http = gmaps_scraper_http_client(
    **settings.gmaps_scraper_http_kwargs()
)

Returns:

Name Type Description
GmapsScraperHTTPKwargs GmapsScraperHTTPKwargs

base_url and timeout ready to

GmapsScraperHTTPKwargs

splat into :func:gmaps_scraper_http_client or

GmapsScraperHTTPKwargs

class:~tempest_fastapi_sdk.HTTPClient.

GmapsScraperHTTPKwargs

Bases: TypedDict

Keyword arguments for gmaps_scraper_http_client and HTTPClient.

Returned by :meth:GmapsScraperSettings.gmaps_scraper_http_kwargs, typed so the splat is statically checked against both :func:~tempest_fastapi_sdk.integrations.places.gmaps_scraper.gmaps_scraper_http_client and :class:~tempest_fastapi_sdk.HTTPClient.

Attributes:

Name Type Description
base_url str

Sidecar base URL (GMAPS_SCRAPER_URL).

timeout float

Per-request HTTP timeout in seconds (GMAPS_SCRAPER_TIMEOUT).

GoogleDriveSettings

Bases: BaseAppSettings

Service account and target folder of the Google Drive upload backend.

Mirrors the arguments of :meth:tempest_fastapi_sdk.integrations.storage.google_drive.GoogleDriveUploadStorage.from_service_account.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

GOOGLE_DRIVE_CREDENTIALS_JSON and GOOGLE_DRIVE_CREDENTIALS_PATH describe the same service account through different channels, as in :class:FirebaseSettings: when both are set the inline JSON wins.

Attributes:

Name Type Description
GOOGLE_DRIVE_CREDENTIALS_PATH str

Path to the service-account JSON key file. Default: "".

GOOGLE_DRIVE_CREDENTIALS_JSON str

The service-account JSON inline. Default: "".

GOOGLE_DRIVE_FOLDER_ID str

Id of the folder files are written into — the last path segment of the folder's URL. It must be shared with the service account's client_email. Default: "".

GOOGLE_DRIVE_DRIVE_ID str

Id of the Shared Drive that holds the folder, when it lives in one. Optional: lookups then search that drive only instead of every drive the account can see. Default: "".

google_drive_kwargs

google_drive_kwargs() -> GoogleDriveStorageKwargs

Map these settings onto GoogleDriveUploadStorage.from_service_account.

Empty strings become None so an unset variable leaves the factory's own handling in place::

storage = GoogleDriveUploadStorage.from_service_account(
    **settings.google_drive_kwargs()
)

Returns:

Name Type Description
GoogleDriveStorageKwargs GoogleDriveStorageKwargs

folder_id, credentials_path,

GoogleDriveStorageKwargs

credentials_json and drive_id.

GoogleDriveStorageKwargs

Bases: TypedDict

Keyword arguments for GoogleDriveUploadStorage.from_service_account.

Returned by :meth:GoogleDriveSettings.google_drive_kwargs, typed so the splat is checked against the factory's signature.

Attributes:

Name Type Description
folder_id str

GOOGLE_DRIVE_FOLDER_ID.

credentials_path str | None

GOOGLE_DRIVE_CREDENTIALS_PATH, or None when unset.

credentials_json str | None

GOOGLE_DRIVE_CREDENTIALS_JSON, or None when unset.

drive_id str | None

GOOGLE_DRIVE_DRIVE_ID, or None when unset.

GooglePlacesSettings

Bases: BaseAppSettings

Credentials, endpoint and kill-switch for Google Places API (New) v1.

Mirrors the arguments of :func:tempest_fastapi_sdk.integrations.places.google_places.google_places_http_client.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
GOOGLE_PLACES_ENABLED bool

Kill-switch for the Google Places integration. Setting it to False skips the production checks below and appends "google_places" to :meth:disabled_integrations. Default: True.

GOOGLE_PLACES_API_KEY str

Google Cloud API key sent in the X-Goog-Api-Key header. Default: "".

GOOGLE_PLACES_BASE_URL str

Root URL of the Google Places API (New) v1. Default: "https://places.googleapis.com".

GOOGLE_PLACES_TIMEOUT float

Per-request HTTP timeout in seconds. Must be positive and finite. Default: 10.0.

google_places_http_kwargs

google_places_http_kwargs() -> GooglePlacesHTTPKwargs

Map these settings onto :func:google_places_http_client.

Intended to be splatted directly inside the application lifespan::

async with google_places_http_client(
    **settings.google_places_http_kwargs()
) as http:
    app.state.places = GooglePlacesClient(http)
    yield

Returns:

Name Type Description
GooglePlacesHTTPKwargs GooglePlacesHTTPKwargs

api_key, base_url and timeout.

production_violations

production_violations() -> list[str]

Refuse a production boot when Google Places is enabled without a key.

Skipped when GOOGLE_PLACES_ENABLED is False.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus violations when

list[str]

GOOGLE_PLACES_API_KEY or GOOGLE_PLACES_BASE_URL is empty

list[str]

while GOOGLE_PLACES_ENABLED is True.

disabled_integrations

disabled_integrations() -> list[str]

Append "google_places" when GOOGLE_PLACES_ENABLED is off.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus "google_places" when off.

GooglePlacesHTTPKwargs

Bases: TypedDict

Keyword arguments for google_places_http_client.

Returned by :meth:GooglePlacesSettings.google_places_http_kwargs, typed so the splat is checked against :func:~tempest_fastapi_sdk.integrations.places.google_places.google_places_http_client.

Attributes:

Name Type Description
api_key str

Google Cloud API key sent in X-Goog-Api-Key (GOOGLE_PLACES_API_KEY).

base_url str

Google Places API root URL (GOOGLE_PLACES_BASE_URL).

timeout float

Per-request timeout in seconds (GOOGLE_PLACES_TIMEOUT).

AlertSettings

Bases: BaseAppSettings

Who is told, and how often, when the API or the app fails badly.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
ALERT_ENABLED bool

Master switch. Default: False.

ALERT_EMAILS list[str]

Recipients, as a JSON list in the environment (ALERT_EMAILS='["ops@example.com"]'), the same shape as CORS_ORIGINS. Default: [].

ALERT_WINDOW_SECONDS int

Silence window per fingerprint. Default: 900 (15 minutes).

ALERT_MAX_PER_WINDOW int

Deliveries allowed per window across every fingerprint of one source (API, app). Default: 20.

ALERT_SUBJECT_PREFIX str

Prepended to every subject. Default: "[ALERT]".

ALERT_APP_MIN_SEVERITY AppErrorSeverityEnum

Lowest app-report severity that alerts. Default: fatal.

alert_kwargs

alert_kwargs() -> AlertKwargs

Map these settings onto :class:AlertNotifier.

Example::

notifier = AlertNotifier(
    EmailAlertChannel(email, **settings.email_alert_kwargs()),
    static_recipients(settings.ALERT_EMAILS),
    **settings.alert_kwargs(),
)

Returns:

Name Type Description
AlertKwargs AlertKwargs

enabled, window_seconds and

AlertKwargs

max_per_window.

email_alert_kwargs

email_alert_kwargs() -> EmailAlertKwargs

Map these settings onto :class:EmailAlertChannel.

Returns:

Name Type Description
EmailAlertKwargs EmailAlertKwargs

subject_prefix.

disabled_integrations

disabled_integrations() -> list[str]

Append "alerts" when ALERT_ENABLED is off.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus "alerts" when off.

AlertKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.alerts.AlertNotifier.

Returned by :meth:AlertSettings.alert_kwargs. The channel and the recipients are positional and stay with the caller: they are objects, not settings.

Attributes:

Name Type Description
enabled bool

ALERT_ENABLED.

window_seconds int

ALERT_WINDOW_SECONDS.

max_per_window int

ALERT_MAX_PER_WINDOW.

EmailAlertKwargs

Bases: TypedDict

Keyword arguments for :class:~tempest_fastapi_sdk.alerts.EmailAlertChannel.

Returned by :meth:AlertSettings.email_alert_kwargs.

Attributes:

Name Type Description
subject_prefix str

ALERT_SUBJECT_PREFIX.

ApifySettings

Bases: BaseAppSettings

Credentials, endpoint and kill-switch for the Apify REST API v2 client.

Mirrors the arguments of :func:tempest_fastapi_sdk.integrations.scraping.apify.apify_http_client.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
APIFY_ENABLED bool

Kill-switch for the Apify integration. Setting it to False skips the production check below and appends "apify" to :meth:disabled_integrations. Default: True.

APIFY_API_TOKEN str

Personal API token sent as Authorization: Bearer <token>. Never placed in the URL query string. Default: "".

APIFY_BASE_URL str

Base URL of the Apify REST API v2. Default: "https://api.apify.com/v2".

APIFY_TIMEOUT float

Per-request HTTP timeout in seconds for synchronous actor runs. Default: 120.0.

apify_http_kwargs

apify_http_kwargs() -> ApifyHttpKwargs

Map these settings onto :func:apify_http_client.

Example::

client = ApifyClient(apify_http_client(**settings.apify_http_kwargs()))

Returns:

Name Type Description
ApifyHttpKwargs ApifyHttpKwargs

api_token, base_url and timeout.

production_violations

production_violations() -> list[str]

Refuse a production boot when Apify is enabled without a token.

Skipped when APIFY_ENABLED is False.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus one when

list[str]

APIFY_API_TOKEN is empty while APIFY_ENABLED is True.

disabled_integrations

disabled_integrations() -> list[str]

Append "apify" when APIFY_ENABLED is off.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus "apify" when off.

ApifyHttpKwargs

Bases: TypedDict

Keyword arguments for apify_http_client.

Returned by :meth:ApifySettings.apify_http_kwargs, typed so the splat is checked against :func:~tempest_fastapi_sdk.integrations.scraping.apify.apify_http_client.

Attributes:

Name Type Description
api_token str

APIFY_API_TOKEN.

base_url str

APIFY_BASE_URL.

timeout float

APIFY_TIMEOUT.

LinkedInSettings

Bases: BaseAppSettings

LinkedIn OAuth credentials, API version pin and kill-switch.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
LINKEDIN_ENABLED bool

Kill-switch for the integration. False skips :meth:production_violations, appends "linkedin" to :meth:disabled_integrations, and forwards enabled=False in :meth:linkedin_oauth_kwargs. Default: True.

LINKEDIN_CLIENT_ID str

OAuth 2.0 application client id from the LinkedIn Developer Portal. Default: "".

LINKEDIN_CLIENT_SECRET str

OAuth 2.0 application client secret. Default: "".

LINKEDIN_API_VERSION str

YYYYMM value sent in the LinkedIn-Version header. Default: "202505".

LINKEDIN_TIMEOUT float

Per-request HTTP timeout in seconds. Must be greater than zero. Default: 30.0.

linkedin_oauth_kwargs

linkedin_oauth_kwargs() -> LinkedInOAuthKwargs

Map these settings onto LinkedInOAuthClient.

Example::

oauth = LinkedInOAuthClient(**settings.linkedin_oauth_kwargs())

Returns:

Name Type Description
LinkedInOAuthKwargs LinkedInOAuthKwargs

client_id, client_secret,

LinkedInOAuthKwargs

timeout and enabled.

linkedin_http_kwargs

linkedin_http_kwargs(access_token: str) -> LinkedInHTTPKwargs

Map these settings plus a per-user token onto linkedin_http_client.

Example::

http = linkedin_http_client(**settings.linkedin_http_kwargs(token))
client = LinkedInClient(http, enabled=settings.LINKEDIN_ENABLED)

Parameters:

Name Type Description Default
access_token str

OAuth 2.0 bearer token for the target member or organization administrator.

required

Returns:

Name Type Description
LinkedInHTTPKwargs LinkedInHTTPKwargs

access_token, api_version and

LinkedInHTTPKwargs

timeout.

production_violations

production_violations() -> list[str]

Refuse a production boot when LinkedIn OAuth credentials are missing.

Skipped entirely when LINKEDIN_ENABLED is False.

Returns:

Type Description
list[str]

list[str]: Parent violations plus missing LINKEDIN_CLIENT_ID

list[str]

or LINKEDIN_CLIENT_SECRET entries.

disabled_integrations

disabled_integrations() -> list[str]

Append "linkedin" when LINKEDIN_ENABLED is off.

Returns:

Type Description
list[str]

list[str]: Parent entries plus "linkedin" when disabled.

LinkedInOAuthKwargs

Bases: TypedDict

Keyword arguments for LinkedInOAuthClient.__init__.

Returned by :meth:LinkedInSettings.linkedin_oauth_kwargs, typed so the splat is checked against the client's signature.

Attributes:

Name Type Description
client_id str

LINKEDIN_CLIENT_ID.

client_secret str

LINKEDIN_CLIENT_SECRET.

timeout float

LINKEDIN_TIMEOUT.

enabled bool

LINKEDIN_ENABLED.

LinkedInHTTPKwargs

Bases: TypedDict

Keyword arguments for linkedin_http_client.

Returned by :meth:LinkedInSettings.linkedin_http_kwargs, typed so the splat is checked against the factory's signature.

Attributes:

Name Type Description
access_token str

Per-user OAuth 2.0 bearer token.

api_version str

LINKEDIN_API_VERSION.

timeout float

LINKEDIN_TIMEOUT.

StorageBucketCredential

Bases: BaseModel

The access key and secret key one bucket is reached with.

The secret is a :class:~pydantic.SecretStr, so repr, str and model_dump print **********; validation errors leave the input out (hide_input_in_errors), so a typo in the JSON does not echo the secret into the boot log. Unknown keys are refused, which turns {"access_key": ..., "secret": ...} into an error instead of a credential without a secret.

Attributes:

Name Type Description
access_key str

The S3 access key. Must not be empty.

secret_key SecretStr

The S3 secret key. Must not be empty.

ZapSettings

Bases: BaseAppSettings

Configuration for the zap-api WhatsApp gateway.

Groups the gateway URL, outbound API key, inbound webhook signing secret, request timeout and kill-switch into a single mixin that composes with :class:~tempest_fastapi_sdk.settings.EnvironmentSettings and splats directly into :func:~tempest_fastapi_sdk.integrations.messaging.zap.zap_http_client.

Each attribute below is also the name of the environment variable that sets it (matched case-sensitively, no prefix).

Attributes:

Name Type Description
ZAP_ENABLED bool

Kill-switch for the whole integration. False skips the production checks below and lists "zap" in :meth:disabled_integrations. Default: True.

ZAP_BASE_URL str

Root URL of the zap-api gateway (for example "http://127.0.0.1:3000"). Default: "".

ZAP_API_KEY str

Consumer API key sent in the x-api-key header. Default: "".

ZAP_WEBHOOK_SECRET str

HMAC-SHA256 secret used to verify incoming x-zap-signature headers. Empty rejects webhook construction via make_zap_webhook_dependency and make_zap_webhook_router. Default: "".

ZAP_TIMEOUT float

Per-request timeout in seconds for outbound gateway calls. Default: 10.0.

zap_webhook_secret property

zap_webhook_secret: str | None

Return ZAP_WEBHOOK_SECRET when configured, or None when empty.

Returns:

Type Description
str | None

str | None: The webhook signing secret, or None when

str | None

ZAP_WEBHOOK_SECRET is empty.

zap_http_kwargs

zap_http_kwargs() -> ZapHttpKwargs

Map these settings onto zap_http_client.

Intended to be splatted directly inside the application lifespan::

async with zap_http_client(**settings.zap_http_kwargs()) as http:
    app.state.zap = ZapClient(http)
    yield

Returns:

Name Type Description
ZapHttpKwargs ZapHttpKwargs

base_url, api_key and timeout.

production_violations

production_violations() -> list[str]

Refuse a production boot when zap-api is enabled without credentials.

Skipped entirely when ZAP_ENABLED is off.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus entries when ZAP_BASE_URL

list[str]

or ZAP_API_KEY is empty.

disabled_integrations

disabled_integrations() -> list[str]

Append "zap" when ZAP_ENABLED is off.

Returns:

Type Description
list[str]

list[str]: The parent's entries, plus "zap" when off.

ZapHttpKwargs

Bases: TypedDict

Keyword arguments for zap_http_client.

Returned by :meth:ZapSettings.zap_http_kwargs, typed so the splat is checked against the factory's signature.

Attributes:

Name Type Description
base_url str

Gateway root URL (ZAP_BASE_URL).

api_key str

Consumer API key sent in x-api-key (ZAP_API_KEY).

timeout float

Per-request timeout in seconds (ZAP_TIMEOUT).