Skip to content

API reference

Generated reference documentation for each package. The pages are rebuilt and published with this site from main.

Language Reference Generated by
TypeScript TypeScript API TypeDoc
Rust Rust API · docs.rs rustdoc
Go pkg.go.dev Go doc comments
Python below mkdocstrings
Java Java API Javadoc

Build them locally with make docs (per language: make -C <lang> docs).

Python

Grow Codes SDK for Infisical.

from grow_infisical import InfisicalClient, InfisicalConfig client = InfisicalClient.from_env() # doctest: +SKIP client.secrets.get_secret("API_KEY").value.reveal() # doctest: +SKIP

ApiVersionSetting module-attribute

ApiVersionSetting = Literal['auto', 'v4', 'v3']

Secrets API version: detected at run time (auto) or forced.

SecretType module-attribute

SecretType = Literal['shared', 'personal']

shared (default) or the caller's personal override (user tokens only).

TokenKind module-attribute

TokenKind = Literal['identity', 'user', 'serviceToken']

Token kind (wire values shared by every language: identity, user, serviceToken).

AccessToken dataclass

An access token returned by a login or renewal (repr hides the token).

AsyncBaseSecretsProvider

Bases: ABC

Async counterpart of :class:BaseSecretsProvider (async primitives).

After :meth:aclose every call raises :class:CancelledError ("client is closed").

closed property

closed: bool

True once :meth:aclose was called.

aclose async

aclose() -> None

Stop every watcher started by this provider; later calls raise CANCELLED (idempotent).

ensure_open

ensure_open(op: str) -> None

Raise :class:CancelledError (": client is closed") after :meth:aclose.

Service methods that do not go through the base operations can call it first.

load_env async

load_env(source: str | Mapping[str, str], *, override: bool = False, prefix: str = '', environ: MutableMapping[str, str] | None = None) -> dict[str, str]

See :meth:BaseSecretsProvider.load_env.

watch

watch(name: str, interval_s: float | timedelta, on_change: OnChange, *, on_error: OnError | None = None, version: str | None = None, path: str | None = None) -> AsyncWatchHandle

Start an asyncio task polling name (call from a running event loop).

AsyncFolders

Bases: AsyncModule, _FolderOps

Async :class:Folders.

AsyncHttpTransport

Asynchronous transport (one per async client); options as for :class:HttpTransport.

Cancelling the calling task raises :class:CancelledError (an asyncio.CancelledError subclass) so asyncio's cancellation machinery keeps working. Every call after :meth:aclose raises :class:CancelledError ("client is closed").

aclose async

aclose() -> None

Close the connection pool and abort backoff sleeps (idempotent).

request async

request(req: Request) -> Response

Send req with retries; return the response or raise the mapped error.

AsyncImports

Bases: AsyncModule, _ImportOps

Async :class:Imports.

AsyncInfisicalClient

Bases: _ClientBase

Asynchronous Infisical client (same modules and methods, awaitable); use async with or call :meth:aclose.

Cancel a call by cancelling its task: the SDK raises :class:CancelledError, which is also an :class:asyncio.CancelledError.

folders instance-attribute

folders = AsyncFolders(self._runner)

See :attr:InfisicalClient.folders.

imports instance-attribute

imports = AsyncImports(self._runner)

See :attr:InfisicalClient.imports.

projects instance-attribute

projects = AsyncProjects(self._runner)

See :attr:InfisicalClient.projects.

provider instance-attribute

provider = self.secrets_provider()

See :attr:InfisicalClient.provider.

secrets instance-attribute

secrets = AsyncSecrets(self._runner)

See :attr:InfisicalClient.secrets.

tags instance-attribute

tags = AsyncTags(self._runner)

See :attr:InfisicalClient.tags.

aclose async

aclose() -> None

See :meth:InfisicalClient.close.

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> AsyncInfisicalClient

Build a client from GROW_INFISICAL_* and INFISICAL_* variables.

health async

health() -> HealthStatus

See :meth:InfisicalClient.health.

ping async

ping() -> float

See :meth:InfisicalClient.ping.

request async

request(req: Request) -> Response

See :meth:InfisicalClient.request.

secrets_provider

secrets_provider(*, project_id: str | None = None, environment: str | None = None, base_path: str | None = None) -> AsyncInfisicalSecretsProvider

See :meth:InfisicalClient.secrets_provider.

server_version async

server_version() -> str

See :meth:InfisicalClient.server_version.

AsyncInfisicalSecretsProvider

Bases: AsyncBaseSecretsProvider

Async :class:InfisicalSecretsProvider.

base_path property

base_path: str

Base path every name is relative to.

get_all async

get_all(path: str | None = None) -> dict[str, SecretValue]

Every secret directly under path with one list call (imports per config).

locate

locate(name: str, path: str | None = None) -> SecretLocation

Split a provider name into folder path and key.

AsyncProjects

Bases: AsyncModule, _ProjectOps

Async :class:Projects.

AsyncSecretCache

Bases: AsyncBaseSecretsProvider

Async :class:SecretCache; background refreshes run as asyncio tasks.

wait_refreshes async

wait_refreshes() -> None

Wait for background refreshes currently running (useful in tests).

watch

watch(name: str, interval_s: float | timedelta, on_change: OnChange, *, on_error: OnError | None = None, version: str | None = None, path: str | None = None) -> AsyncWatchHandle

Watches the underlying provider directly (bypasses the cache).

AsyncSecrets

Bases: AsyncModule, _SecretOps

Async :class:Secrets.

AsyncSecretsProvider

Bases: Protocol

Asynchronous secrets interface (same methods, awaitable).

AsyncTags

Bases: AsyncModule, _TagOps

Async :class:Tags.

AsyncWatchHandle

Async counterpart of :class:WatchHandle running as an asyncio task.

on_change and on_error may be plain or async callables.

stop

stop() -> None

Stop polling (idempotent).

wait async

wait() -> None

Wait until the task has finished (after :meth:stop).

AuthenticationError

Bases: InfisicalError

Credentials missing or rejected (HTTP 401).

AwsCredentials dataclass

AWS credentials used to sign the STS request (repr hides the secrets).

AwsIamAuth

Bases: IdentityLoginAuth

AWS IAM Auth: signs sts:GetCallerIdentity (SigV4) and posts it to /api/v1/auth/aws-auth/login.

region defaults to AWS_REGION, AWS_DEFAULT_REGION, then us-east-1; credentials (an :class:AwsCredentials or a callable returning one, e.g. a wrapper of the boto3 credential chain) default to AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/ AWS_SESSION_TOKEN. env replaces os.environ for these defaults.

build_login_request

build_login_request(date: datetime | None = None) -> AwsLoginRequest

Build the signed login body for date (default now; exposed for tests).

AwsLoginRequest dataclass

The signed fields of an AWS IAM login body.

to_json

to_json() -> dict[str, str]

The wire form (camelCase).

BaseConfig dataclass

Common, immutable client settings. Durations are float seconds (timedelta accepted).

Service configs subclass this (@dataclass(frozen=True, repr=False)), override url with the service default, add their own fields (Secret for credentials), extend :meth:_env_values and :meth:validate, and list vendor variables in ENV_VENDOR.

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> _C

Build from the environment, then validate.

Precedence: explicit keyword > GROW_INFISICAL_<NAME> > vendor variables > default. env defaults to os.environ; pass a dict in tests.

known_secrets

known_secrets() -> list[str]

Revealed values of every :class:Secret field (used to redact error text).

validate

validate() -> _C

Check the common rules; raise :class:ConfigError. Returns self.

BaseSecretsProvider

Bases: ABC

Implements :class:SecretsProvider on top of five primitives a service provides.

Primitives (opts are the option dataclasses):

  • _fetch_secret(name, GetOptions) -> SecretValue | None (None when missing)
  • _list_secrets(path) -> list[SecretMetadata] (secrets directly under path)
  • _put_secret(name, data: bytes, SetOptions) -> str (new version or "")
  • _remove_secret(name, DeleteOptions) -> None (raise :class:NotFoundError if missing)
  • _fetch_metadata(name, GetOptions) -> SecretMetadata | None

Watchers started with :meth:watch are stopped by :meth:close and, when owner is given (the client's registry), by client.close(). After :meth:close every call raises :class:CancelledError (": client is closed") before any primitive runs.

closed property

closed: bool

True once :meth:close was called.

close

close() -> None

Stop every watcher started by this provider; later calls raise CANCELLED (idempotent).

delete

delete(name: str, *, path: str | None = None, versions: Sequence[str] | None = None, permanent: bool = False) -> None

Delete a secret; :class:NotFoundError when it does not exist.

ensure_open

ensure_open(op: str) -> None

Raise :class:CancelledError (": client is closed") after :meth:close.

Service methods that do not go through the base operations can call it first.

get

get(name: str, *, version: str | None = None, path: str | None = None) -> SecretValue | None

The secret, or None when it does not exist.

get_all

get_all(path: str | None = None) -> dict[str, SecretValue]

Every secret directly under path (non-recursive), keyed by name.

get_bool

get_bool(name: str, *, version: str | None = None, path: str | None = None) -> bool | None

true/false/1/0/yes/no/on/off, None when missing; else ValidationError.

get_json

get_json(name: str, *, version: str | None = None, path: str | None = None) -> Any

Decoded JSON, None when missing; :class:ValidationError when not JSON.

get_many

get_many(names: Sequence[str], *, version: str | None = None, path: str | None = None) -> dict[str, SecretValue]

Values in request order; missing names are omitted.

get_number

get_number(name: str, *, version: str | None = None, path: str | None = None) -> int | float | None

int or float, None when missing; :class:ValidationError otherwise.

list

list(prefix: str | None = None) -> builtins.list[SecretMetadata]

Metadata of the secrets under prefix, sorted by name.

load_env

load_env(source: str | Mapping[str, str], *, override: bool = False, prefix: str = '', environ: MutableMapping[str, str] | None = None) -> dict[str, str]

Export secrets to environment variables; returns {env_name: secret_name}.

source is a path (one variable per secret directly under it, named from the secret name relative to the path, upper-cased, non [A-Z0-9_] → _, plus prefix) or a mapping {env_name: secret_name} (a missing secret raises :class:NotFoundError before anything is set). Existing variables are kept unless override. environ defaults to :data:os.environ.

require

require(name: str, *, version: str | None = None, path: str | None = None) -> SecretValue

The secret; :class:NotFoundError when missing.

set

set(name: str, value: Any, *, path: str | None = None, cas: int | None = None, tags: Mapping[str, str] | None = None, description: str | None = None) -> str

Store value (str, bytes, or JSON-encoded object); returns the new version.

watch

watch(name: str, interval_s: float | timedelta, on_change: OnChange, *, on_error: OnError | None = None, version: str | None = None, path: str | None = None) -> WatchHandle

Poll name every interval_s and call on_change(new, old) on change.

BatchCreateSecret dataclass

One secret of create_secrets.

BatchDeleteSecret dataclass

One secret of delete_secrets (a plain key string is accepted too).

BatchUpdateSecret dataclass

One secret of update_secrets: only the given fields change.

CancelToken

Thread-safe cancellation flag passed to sync calls as cancel=.

Cancelling interrupts an in-flight request (the call returns immediately with :class:CancelledError; the abandoned HTTP exchange finishes in the background) and any retry backoff sleep.

cancel

cancel() -> None

Request cancellation (idempotent).

on_cancel

on_cancel(callback: Callable[[], None]) -> Callable[[], None]

Run callback on cancellation (now if already cancelled); returns an unregister.

wait

wait(timeout: float | None = None) -> bool

Block until cancelled or timeout; return whether the token is cancelled.

CancelledError

Bases: InfisicalError, CancelledError

The caller cancelled the operation (task cancel, :class:CancelToken, client close).

Also an :class:asyncio.CancelledError so asyncio keeps treating the task as cancelled.

ConfigError

Bases: InfisicalError

Invalid or missing configuration.

ConflictError

Bases: InfisicalError

Conflict or failed precondition (HTTP 409, 412, CAS mismatch).

EnvReader

Reads GROW_<KEY_UPPER>_<NAME> and vendor variables from an injectable mapping.

Every getter returns None when no variable is set (empty strings count as unset). A present but invalid value raises :class:ConfigError that names the variable, never its value.

duration

duration(name: str, vendor_names: Iterable[str] = ()) -> builtins.float | None

Duration in seconds.

lookup

lookup(name: str, vendor_names: Iterable[str] = ()) -> tuple[str, str] | None

Return (variable_name, raw_value) for the first variable that is set.

Environment dataclass

An environment of a project.

ErrorCode

Bases: str, Enum

Canonical error codes; the value is the wire form used by the conformance suite.

ErrorInfo dataclass

Passed to Hooks.on_error; error is the (redacted) SDK error.

Folder dataclass

A folder.

Folders

Bases: SyncModule, _FolderOps

Folders of a project environment (client.folders).

HealthStatus dataclass

Result of health(); status is ok/degraded/unhealthy/unreachable or a vendor word.

Hooks dataclass

Optional callbacks invoked on every attempt. Exceptions raised by hooks are ignored.

HttpTransport

Synchronous transport (one per client).

Service options (all optional):

  • request_id_headers: vendor request id headers, checked before :data:REQUEST_ID_HEADERS.
  • retry_after_headers: headers read (in order) for the delay a 429/503 response asks for; default ("retry-after",), e.g. ("retry-after", "x-ratelimit-reset"). See :func:retry_after_from_headers.
  • error_mapper: mapper(error, response) returns a service-specific error for an HTTP error response (or None to keep the default). The mapped error is what Hooks.on_error, the retry planner (retry_after) and the caller see; whether a status is retried stays the SPEC rule. Exceptions raised by the mapper are logged and ignored.

Every call after :meth:close raises :class:CancelledError ("client is closed").

close

close() -> None

Close the connection pool and abort backoff sleeps (idempotent).

request

request(req: Request, *, cancel: CancelToken | None = None) -> Response

Send req with retries; return the response or raise the mapped error.

IdentityLoginAuth

Bases: InfisicalAuth

Base of the login-based machine identity methods: login, renew, revoke and refresh.

access_token property

access_token: AccessToken | None

The current access token (None before the first login or after revoke).

alogin async

alogin() -> AccessToken

Async :meth:login.

arenew async

arenew() -> AccessToken

Async :meth:renew.

arevoke async

arevoke() -> None

Async :meth:revoke.

login

login() -> AccessToken

Log in (POST <login_path>) and store the new access token.

login_op

login_op(session: Session) -> Op[AccessToken]

Log in and store the new token (internal).

renew

renew() -> AccessToken

Renew the current token (POST /api/v1/auth/token/renew); store the returned one.

renew_op

renew_op(session: Session) -> Op[AccessToken]

Renew the current token and store the returned one (internal).

revoke

revoke() -> None

Revoke the current token (POST /api/v1/auth/token/revoke); no-op without one.

revoke_op

revoke_op(session: Session) -> Op[None]

Revoke the current token (no-op without one) (internal).

ImportedSecrets dataclass

Secrets reached through one secret import.

Imports

Bases: SyncModule, _ImportOps

Secret imports of a folder (client.imports).

InfisicalAuth

Bases: ABC

An auth method; the client asks it for a token before every authenticated call.

token_kind abstractmethod property

token_kind: TokenKind

Principal kind of the tokens this method produces.

close_op

close_op(session: Session, revoke: bool) -> Op[None]

Release the method (internal); login methods may revoke their token.

invalidate

invalidate() -> None

Forget the current token (the next call logs in again).

known_secrets abstractmethod

known_secrets() -> list[str]

Credential values to redact from errors.

refresh_op abstractmethod

refresh_op(session: Session) -> Op[Secret]

Obtain a fresh token (internal).

valid_token abstractmethod

valid_token(now: float) -> Secret | None

The current token when it needs no refresh, else None (internal).

InfisicalClient

Bases: _ClientBase

Synchronous Infisical client. Thread-safe; use as a context manager or call :meth:close.

Modules: :attr:secrets, :attr:folders, :attr:projects, :attr:tags, :attr:imports, :attr:provider (the SecretsProvider) and :attr:auth. Cancel calls from another thread with with client.cancellable(token): ... or the cancel= argument of the core methods.

folders instance-attribute

folders = Folders(self._runner)

Folders: list/create/update/delete.

imports instance-attribute

imports = Imports(self._runner)

Secret imports.

projects instance-attribute

projects = Projects(self._runner)

Projects and environments.

provider instance-attribute

provider = self.secrets_provider()

The SPEC SecretsProvider for the configured project/environment/path.

secrets instance-attribute

secrets = Secrets(self._runner)

Secrets: list/get/create/update/delete, batch, versions, load_env, export_dotenv.

tags instance-attribute

tags = Tags(self._runner)

Tags.

cancellable

cancellable(token: CancelToken) -> Iterator[CancelToken]

Apply token to every call made by this thread inside the with block.

close

close() -> None

Stop watchers, revoke a login token when revoke_on_close is set and release connections (idempotent).

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> InfisicalClient

Build a client from GROW_INFISICAL_* and INFISICAL_* variables.

health

health(*, cancel: CancelToken | None = None) -> HealthStatus

Unauthenticated liveness (GET /api/status); never raises for an unhealthy or unreachable service (only :class:CancelledError and :class:ConfigError).

ping

ping(*, cancel: CancelToken | None = None) -> float

Authenticated round trip; latency in ms. The route depends on the token kind (:data:PING_PATHS); bad credentials raise :class:AuthenticationError.

request

request(req: Request, *, cancel: CancelToken | None = None) -> Response

Send a raw request through the transport (retries, hooks, redaction; no auth).

secrets_provider

secrets_provider(*, project_id: str | None = None, environment: str | None = None, base_path: str | None = None) -> InfisicalSecretsProvider

A SecretsProvider for another project, environment or base path; its watchers are stopped by :meth:close.

server_version

server_version(*, cancel: CancelToken | None = None) -> str

Always :class:UnsupportedError: Infisical exposes no running version over HTTP.

InfisicalConfig dataclass

Bases: BaseConfig

Immutable settings for :class:~grow_infisical.InfisicalClient.

Common fields (url, timeouts, retry, tls, proxy, headers, user_agent_suffix, hooks, logger) come from :class:BaseConfig. Durations are float seconds; datetime.timedelta is accepted. Credentials accept str and are stored as :class:Secret; repr() never shows them.

Service fields:

  • token — static access token (machine identity token, user JWT or legacy st. service token) sent as Authorization: Bearer.
  • client_id / client_secret — Universal Auth credentials (login + automatic refresh).
  • organization_slug — sent with identity logins (sub-organizations).
  • auth — an explicit auth method (:class:~grow_infisical.UniversalAuth, :class:~grow_infisical.TokenAuth, :class:~grow_infisical.KubernetesAuth, :class:~grow_infisical.AwsIamAuth); wins over token and client_id.
  • project_id, environment (slug, e.g. dev) and secret_path (/) — defaults of every call. A missing project_id/environment raises :class:ConfigError when a call needs it, not at construction.
  • api_version — auto (v4, falling back to v3 when v4 is missing; "" means auto), v4 or v3.
  • expand_secret_references / include_imports — read defaults (both True).
  • revoke_on_close — revoke a login token in close() (False).

Environment (from_env): GROW_INFISICAL_<NAME> first, then the vendor variables of :data:VENDOR_ENV. Names: URL (INFISICAL_API_URL loses one trailing /api), TOKEN, CLIENT_ID, CLIENT_SECRET, PROJECT_ID, ENVIRONMENT, SECRET_PATH, API_VERSION, REVOKE_ON_CLOSE, CONNECT_TIMEOUT, REQUEST_TIMEOUT, TOTAL_TIMEOUT, MAX_RETRIES, CA_CERT, CLIENT_CERT, CLIENT_KEY, INSECURE_SKIP_VERIFY, PROXY.

known_secrets

known_secrets() -> list[str]

Credential values to redact from error messages and logs.

validate

validate() -> _C

Common checks plus service rules; raises :class:ConfigError.

InfisicalSecret dataclass

One secret as returned by the secrets API (repr never shows the value).

InfisicalSecretsProvider

Bases: BaseSecretsProvider

The SPEC §3 SecretsProvider on top of Infisical (client.provider or client.secrets_provider(...)); the environment comes from the config unless given.

base_path property

base_path: str

Base path every name is relative to.

get_all

get_all(path: str | None = None) -> dict[str, SecretValue]

Every secret directly under path with one list call (imports per config).

locate

locate(name: str, path: str | None = None) -> SecretLocation

Split a provider name into folder path and key.

KubernetesAuth

Bases: IdentityLoginAuth

Kubernetes Auth: POST /api/v1/auth/kubernetes-auth/login with a service-account JWT.

Without jwt the token is read from jwt_path at every login.

LoggerLike

Bases: Protocol

Structured logger interface accepted in configuration (SPEC Logger).

NotFoundError

Bases: InfisicalError

Missing record (HTTP 404).

PermissionDeniedError

Bases: InfisicalError

Authenticated but not allowed (HTTP 403).

Project dataclass

A project.

ProjectList dataclass

A page of projects.

Projects

Bases: SyncModule, _ProjectOps

Projects and environments (client.projects).

RateLimitError

Bases: InfisicalError

Too many requests (HTTP 429); retry_after holds the requested delay when known.

Request dataclass

One logical API call (possibly several attempts).

path is joined to the base URL ({name} style values must already be encoded; use :func:urllib.parse.quote); an absolute http:///https:// URL is used as is (for pagination links the service returns; the default headers, config.headers included, are sent there too, so only pass URLs of the same service). json is encoded when not None; content sends raw bytes. idempotent overrides the method rule; an idempotency_key sends the Idempotency-Key header and marks the request idempotent. raise_for_status=False returns error responses instead of raising (retries still apply). Statuses in allow_status are expected answers (a 404 that carries data, a health endpoint's 503): the response is returned at once, like a success, without retries or on_error.

RequestInfo dataclass

Passed to Hooks.on_request; url and headers are redacted.

ResourceRegistry

Holds :class:Stoppable objects; :meth:stop_all stops each once, ignoring errors.

register

register(item: Stoppable) -> None

Track item; when the registry is already closed the item is stopped now.

Response dataclass

A completed HTTP response (body fully read).

json

json() -> Any

Decode the body as JSON; :class:ValidationError when it is not valid JSON.

ResponseInfo dataclass

Passed to Hooks.on_response; headers are the redacted response headers (rate limit headers and the like stay readable).

RetryPolicy dataclass

Retry settings. Durations are seconds (datetime.timedelta is accepted).

Backoff for retry n (0-based) is full jitter: random(0, min(max_backoff, initial_backoff * multiplier ** n)).

random returns a float in [0, 1); inject it in tests for deterministic sleeps.

max_attempts property

max_attempts: int

Total attempts including the first one.

backoff

backoff(retry: int) -> float

Full-jitter sleep in seconds before retry retry (0-based).

backoff_cap

backoff_cap(retry: int) -> float

Upper bound of the jittered sleep before retry retry (0-based).

Secret

Wraps a credential so it never shows up in str/repr/logs.

s = Secret("hunter2") str(s), s.reveal() ('[REDACTED]', 'hunter2')

reveal

reveal() -> str

Return the wrapped value.

SecretActor dataclass

Who wrote a secret version.

SecretCache

Bases: BaseSecretsProvider

Caches reads of a :class:SecretsProvider; writes pass through and invalidate.

  • Entries live ttl_s; negative results (missing secrets) are cached too.
  • Refresh-ahead: a hit after ttl_s * refresh_ahead_factor starts one background refresh.
  • Stale-while-revalidate: up to ttl_s + stale_while_revalidate_s the stale value is returned while one refresh runs.
  • LRU eviction beyond max_entries. clock (monotonic seconds) is injectable; spawn runs background refreshes (default: a daemon thread).
  • :meth:close makes later calls raise :class:CancelledError ("client is closed"); it does not close the wrapped provider.

invalidate

invalidate(name: str) -> None

Drop every cached entry for name.

watch

watch(name: str, interval_s: float | timedelta, on_change: OnChange, *, on_error: OnError | None = None, version: str | None = None, path: str | None = None) -> WatchHandle

Watches the underlying provider directly (bypasses the cache).

SecretImport dataclass

A secret import (secrets of another environment/path visible in a folder).

SecretList dataclass

Result of list_secrets.

SecretLocation dataclass

Where a provider name lives: folder path and key.

SecretMetadata dataclass

Names and metadata of a secret (never its value).

get(meta.name, path=meta.path) fetches the secret the metadata describes.

SecretValue

Redacting wrapper around a secret's bytes.

str()/repr() print SecretValue([REDACTED]); use :meth:reveal, :meth:reveal_bytes or :meth:json to read the value.

fingerprint

fingerprint() -> str

SHA-256 hex digest of the value (used by watch when there is no version).

json

json() -> Any

The value decoded as JSON; :class:ValidationError when it is not JSON.

reveal

reveal() -> str

The value as UTF-8 text; :class:ValidationError for non-UTF-8 binary data.

reveal_bytes

reveal_bytes() -> bytes

The raw bytes.

SecretVersion dataclass

One historical version of a secret.

Secrets

Bases: SyncModule, _SecretOps

Secrets of a project environment (client.secrets).

SecretsProvider

Bases: Protocol

Synchronous secrets interface implemented by every secrets service package.

Tag dataclass

A tag of a project or attached to a secret.

Tags

Bases: SyncModule, _TagOps

Tags of a project (client.tags).

TimeoutError

Bases: InfisicalError

A connect, request or total deadline was exceeded (also HTTP 408, 504).

TlsConfig dataclass

TLS settings. insecure_skip_verify is for tests only and logs a warning once.

TokenAuth

Bases: InfisicalAuth

A static token: machine identity token (Token Auth), user JWT or legacy service token.

kind overrides the detected :data:TokenKind (see :func:detect_token_kind).

token property

token: Secret

The static token.

UnavailableError

Bases: InfisicalError

Network error or server unavailable (HTTP 500, 502, 503).

UniversalAuth

Bases: IdentityLoginAuth

Universal Auth (client id + client secret): POST /api/v1/auth/universal-auth/login.

UnsupportedError

Bases: InfisicalError

The service or deployment does not offer this capability (HTTP 501, missing API).

ValidationError

Bases: InfisicalError

Bad input (HTTP 400, 413, 422, other 4xx, client-side validation).

WatchHandle

Polls fetch every interval_s in a daemon thread and reports changes.

The first successful fetch is the baseline; later fetches whose version (or SHA-256 when unversioned) differ call on_change(new, old), including deletion (new is None). Errors (from fetching or from on_change) go to on_error and polling continues. A :class:CancelledError from fetching (the provider or client was closed) ends the watcher quietly (:attr:stopped becomes true), like the async watcher.

join

join(timeout: float | None = None) -> None

Wait for the watcher thread to finish (after :meth:stop).

stop

stop() -> None

Stop polling (idempotent, does not wait for an in-flight fetch).

apoll_until async

apoll_until(fn: Callable[[], Awaitable[T | None]], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', clock: Callable[[], float] = time.monotonic) -> T

Async :func:poll_until; fn is an async callable.

detect_token_kind

detect_token_kind(token: str) -> TokenKind

st.… → legacy service token; a JWT with authTokenType: accessToken → user token; everything else → machine identity token.

dotenv_quote

dotenv_quote(value: str) -> str

Quote a value for a dotenv file: "…" with \, ", LF and CR escaped.

env_var_name

env_var_name(name: str, path: str | None, prefix: str) -> str

Variable name for secret name listed under path.

The name relative to path is upper-cased and every character outside [A-Z0-9_] becomes _; prefix is prepended.

error_for_code

error_for_code(code: ErrorCode | str) -> type[InfisicalError]

Return the error class for a code (ErrorCode member or wire value).

error_from_status

error_from_status(status: int, operation: str, *, content: bytes = b'', headers: Headers | None = None, known_secrets: list[str] | None = None, retry_after: float | None = None, request_id_headers: Sequence[str] = ()) -> ServiceError

Map an HTTP error status to the SPEC 2.1 error with a redacted, truncated message.

request_id_headers are checked before the default :data:REQUEST_ID_HEADERS.

format_dotenv

format_dotenv(values: Mapping[str, str]) -> str

Render key → value pairs as a dotenv document (KEY="value" lines sorted by key).

get_logger

get_logger() -> logging.Logger

The package logger (LOGGER_NAME), silent by default (NullHandler).

new_idempotency_key

new_idempotency_key() -> str

A random key for the Idempotency-Key header.

parse_bool

parse_bool(text: str) -> bool

Parse true/false/1/0/yes/no/on/off (case-insensitive); raise :class:ValueError.

parse_duration

parse_duration(text: str) -> float

Parse a duration into seconds.

Accepts integer milliseconds ("1500" → 1.5) or Go-style units ("500ms", "10s", "2m", "1h", "1m30s"). Raises :class:ValueError for anything else.

parse_retry_after

parse_retry_after(value: str | None, *, now: Callable[[], float] = time.time) -> float | None

Parse Retry-After as delta seconds or an HTTP-date; return seconds (>= 0) or None.

poll_until

poll_until(fn: Callable[[], T | None], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic) -> T

Call fn every interval_s until it returns a ready value; return that value.

A value is ready when it is not None and predicate(value) is true (without a predicate: not an empty container). Retryable SDK errors raised by fn are remembered and polling continues; other errors propagate. Raises :class:TimeoutError after timeout_s.

redact_fields

redact_fields(value: Any, extra_keys: Iterable[str] = ()) -> Any

Recursively redact values whose key looks sensitive in nested mappings and lists.

redact_headers

redact_headers(headers: Mapping[str, str] | Iterable[tuple[str, str]]) -> dict[str, str]

Copy of headers with sensitive values replaced by [REDACTED].

redact_text

redact_text(text: str, known_secrets: Iterable[str | Secret | None] = ()) -> str

Replace every known secret value (length >= 4) in text with [REDACTED].

redact_url

redact_url(url: str) -> str

Redact user info and every query value (all values, not only sensitive ones).

Query names are kept so the URL stays useful in logs.

resolve_auth

resolve_auth(config: InfisicalConfig) -> InfisicalAuth | None

The auth method of a config: auth > token > client_id/client_secret.

retry_after_from_headers

retry_after_from_headers(headers: Headers | Mapping[str, str], names: Sequence[str] = RETRY_AFTER_HEADERS, *, now: Callable[[], float] = time.time) -> float | None

Server requested delay in seconds from the first of names that parses.

Retry-After is delta seconds or an HTTP-date. Other headers (X-RateLimit-Reset, RateLimit-Reset …) may be delta seconds or a Unix timestamp in seconds or milliseconds; timestamps are turned into the remaining delay.

sign_aws_request

sign_aws_request(*, method: str, host: str, path: str, region: str, service: str, headers: Mapping[str, str], body: str, access_key_id: str, secret_access_key: str, date: datetime, query: str = '') -> dict[str, str]

Sign a request with AWS Signature Version 4.

Returns the headers to send: headers plus Host (when missing), X-Amz-Date and Authorization. path is already URI-encoded; query is the raw query string.

to_seconds

to_seconds(value: float | timedelta) -> float

Normalise a duration given as float seconds or :class:datetime.timedelta.

truncate

truncate(text: str, limit: int = 300) -> str

Truncate text to limit characters (adds an ellipsis when cut).

user_agent

user_agent(suffix: str | None = None) -> str

grow-codes-<key>/<version> (python) plus <suffix> when given.