Skip to content

Reference

Calling APIs

Credential-injected provider calls, scope discovery, and user-defined trace spans.

Provider calls execute through Alter. Credentials stay in the backend, where policy and approval requirements are enforced.

A provider 4xx or 5xx comes back as a result, not an exception. Check status_code before reading the body.

proxy_request() sends the full request to Alter for server-side execution. The backend resolves the credential, calls the provider, and either returns the response synchronously or returns a PendingApproval if the grant requires human-in-the-loop approval.

Use it when:

  • The grant has an HITL approval policy attached.
  • The workload cannot hold the provider connection open (serverless cold starts, MCP tool calls).
  • Audit / compliance requires the credential to never leave the backend perimeter.

For the common case of “I have a credential, call this URL”, use request() instead.

async def proxy_request(
method: HttpMethod | str,
url: str,
*,
grant_id: str | None = None,
provider: str | None = None,
account: str | None = None,
label: str | None = None,
json: dict | list | str | bool | int | float | None = None,
body: bytes | str | None = None,
extra_headers: dict[str, str] | None = None,
query_params: dict[str, Any] | None = None,
path_params: dict[str, str] | None = None,
reason: str | None = None,
context: dict[str, str] | None = None,
caller: str | None = None,
user_token: str | None = None,
app_user_id: str | None = None,
) -> ApprovalResult | PendingApproval

proxy_request() takes the same arguments as request(), by the same names. The differences come from the execution model: pass JSON as json or raw bytes/UTF-8 text as body (mutually exclusive, up to 5 MiB), auth headers are rejected, header names must be HTTP tokens, the URL as Alter sends it is limited to 65,536 encoded characters (query_too_long; request() applies the same limit to url with its query_params and raises AlterValueError before sending), and the return type is an ApprovalResult / PendingApproval instead of a live response.

ParameterTypeDefaultDescription
methodHttpMethod | str—HTTP method.
urlstr—Full provider URL. Supports {name} placeholders resolved via path_params.
grant_idstr | NoneNoneDirect-mode grant identifier. Exactly one of grant_id or provider must be supplied — proxy_request() shares the same resolution contract as request(): one match resolves, zero raises a not-found error, several raise AmbiguousGrantError.
providerstr | NoneNoneIdentity-mode key (e.g. "provider-id", or a managed-secret provider’s slug). Resolves the user via user_token (or the client’s user_token_getter); for an agent caller, disambiguate delegations with app_user_id. Mutually exclusive with grant_id.
accountstr | NoneNoneAccount disambiguator for provider resolution.
labelstr | NoneNoneSibling-grant disambiguator for provider resolution (the resolution key is provider + label). Only valid alongside provider.
jsondict | list | str | bool | int | float | NoneNoneJSON-serializable request body (same argument name as request()). None omits the body. Numbers must be finite.
bodybytes | str | NoneNoneRaw bytes or UTF-8 text, up to 5 MiB; mutually exclusive with json.
extra_headersdict[str, str] | NoneNoneNon-auth request headers (same argument name as request()). Authorization, Cookie, x-api-key, x-amz-security-token are rejected — the backend injects the credential at execution time.
query_paramsdict[str, Any] | NoneNoneQuery string parameters. The URL as Alter sends it must be at most 65,536 characters once percent-encoded: these parameters merged in (repeated list values and multi-byte characters count in full), plus any query-parameter credential Alter adds. A longer one is refused with query_too_long (65,536 is the most Alter’s HTTP client will send). The provider may apply a lower limit of its own.
path_paramsdict[str, str] | NoneNoneValues substituted into {name} placeholders in url. URL-encoded.
reasonstr | NoneNoneAudit reason.
contextdict[str, str] | NoneNoneAudit-correlation context (same shape and limits as request()). Falls back to the ambient context from Agent.trace() / @alter_tool / @alter.tool() when omitted.
callerstr | NoneNonePer-call override of the client’s caller identifier.
user_tokenstr | NoneNonePer-call user JWT for identity mode. Wins over user_token_getter. Valid in both addressing modes.
app_user_idstr | NoneNonePer-call user identifier for agent-delegation disambiguation. Only valid with provider resolution.

Returns: ApprovalResult for synchronous (non-HITL) execution, or PendingApproval when the grant requires approval (HTTP 202).

  • The provider response body is buffered by the backend and base64-encoded, up to 5 MiB. A larger response is never returned cut: proxy_request() raises ProviderResponseTooLargeError, which carries the provider’s status_code and headers. The provider did answer, so a write may have happened; do not resend a non-idempotent call to recover. Use proxy_stream_request() for downloads, large responses and Server-Sent Events. WebSockets are not supported on the proxy.
  • Auth and cookie-related provider response headers are stripped before the SDK receives the response. Flows that depend on Set-Cookie, WWW-Authenticate, or returned authorization headers may need request() or the provider client directly.
  • Managed-secret proxy calls require destination hosts to be configured on the provider. If the allowlist is missing or does not match the requested host, the call is blocked before the credential is injected.
  • Fields Alter fills with the credential belong to Alter. Every header and query parameter the grant’s credential is injected into (the primary header, and each additional injection rule’s header or query parameter, including a rule with no value for this credential) is removed from the request before the credential is added, so it carries Alter’s value or nothing. This applies to every proxied call; on a call that requires approval, setting one of these fields is refused up front with credential_slot_in_request instead. Header names must be HTTP tokens (no spaces or separators); any other name is rejected.
  • A binary body is sent as given, up to 5 MiB. It is refused with proxy_body_uninspectable when a policy rule needs to read the body (on GraphQL, any operation, family or parameter rule does, unless the provider’s multipart GraphQL body is registered for inspection) and when the call requires approval, because an approver could not see it. A binary GraphQL body carrying a credential operation or credential-bearing selection is refused with credential_minting_refused. On a GraphQL endpoint that can return a credential, a binary body is forwarded without rules only when it is UTF-8 application/json or application/graphql (uncompressed); any other binary body is refused with credential_minting_refused, except a multipart body the provider registers for inspection, which is judged on the GraphQL document in its parts. An upload to a GraphQL endpoint is refused with proxy_body_uninspectable. Two binary bodies are read by policy from the exact bytes sent (an AI review rule still refuses them): a UTF-8 form body declared application/x-www-form-urlencoded on an operation whose provider documents a form-encoded body, and a UTF-8 text body an operation documents as one of its forms; see Fail-closed. An operation allowlist denies a request whose operation it cannot name with operation_unclassified (403), whatever its body. Otherwise the call runs. Payload capture never includes a binary request or that call’s response.
  • proxy_request() does not automatically retry the initial call. Add application-level retry/backoff for network failures and timeouts. For HITL grants, retry carefully because submitting the same call again can create another pending approval.

Raises:

  • AlterValueError — neither grant_id nor provider supplied (or both), an identifier value is an empty string, account/label/app_user_id supplied without provider, an unresolved {name} placeholder left in url after path_params, payload not JSON-serializable, header validation failure, forbidden auth header.
  • BackendError and subclasses — backend-side failure or grant-state error.
  • ProxyTransferError — a binary body or stream was refused.
  • NetworkError, TimeoutError — connectivity failures.

When the grant has no approval requirement, the backend executes the call and returns the response:

from alter_sdk import App, HttpMethod
from alter_sdk.models import ApprovalResult
app = App(api_key="alter_rk_…")
result = await app.proxy_request(
HttpMethod.POST,
"https://api.provider.example/v1/actions",
grant_id=grant_id,
json={"resource_id": "resource_123"},
)
assert isinstance(result, ApprovalResult)
print(result.status_code, result.body_json())

When the grant has requires_approval configured, the backend returns 202 and a PendingApproval. Pass approval_id to await_approval() to block until the approver decides.

from alter_sdk.models import ApprovalResult, PendingApproval
result = await app.proxy_request(
"POST",
"https://api.provider.example/v1/restricted-actions",
grant_id=grant_id,
json={"resource_id": "resource_abc"},
reason="operator_requested_action",
)
if isinstance(result, PendingApproval):
notify_approver(result.approval_url)
final = await app.await_approval(
str(result.approval_id),
timeout=600.0,
)
assert isinstance(final, ApprovalResult)
print(final.body_json())

ApprovalResult stores the body base64-encoded. Use the helpers:

result.body_bytes() # raw bytes
result.body_text() # UTF-8 decode
result.body_text("latin-1")
result.body_json() # parse JSON
result.status_code # HTTP status from the provider
result.headers # response headers (dict)
result.duration_ms # provider round-trip milliseconds, or None

See ApprovalResult for the full model.

The backend rejects requests that try to inject credentials in headers:

  • Authorization
  • Cookie
  • x-api-key
  • x-amz-security-token

The backend injects the correct credential at execution time based on the grant.

A header name repeated in another spelling (Dropbox-API-Arg together with dropbox-api-arg) is rejected as well, with a 422 duplicate_header_spelling: the provider would read the two lines as one header while a policy rule could judge only one of them.

Method-override headers are rejected too, for a different reason:

  • x-http-method
  • x-http-method-override
  • x-method-override

These carry no credential, but some providers (OData V2 services such as SAP S/4HANA) honour them as an override of the real HTTP verb. Policy rules are evaluated against the verb sent on the wire, so a tunnelled verb would let a request be authorized as one operation and executed as another. Send the intended method directly instead.

These advanced, disabled-by-default methods are documented only in the non-proxy reference.

The scopes namespace exposes the backend’s scope-catalog discovery endpoint. The catalog is static metadata for a given backend version — use it to introspect what scopes exist before calling keys.derive(), or to render a scope picker in a custom dashboard.

Both App and Agent expose scopes.

async def list() -> ScopeCatalog

Returns: ScopeCatalog — scope_version, per-resource verb lists, action verb list, deprecated scopes.

Raises: BackendError on backend reachability or response-shape failure.

from alter_sdk import App
app = App(api_key="alter_rk_…")
catalog = await app.scopes.list()
print("scope_version:", catalog.scope_version)
for resource, info in catalog.resources.items():
print(f" {resource}: {info.verbs}")
print("action verbs:", catalog.action_verbs)
print("deprecated:", catalog.deprecated)

The catalog is not cached by the SDK — callers are expected to call list() on demand. No scope is required to read the catalog.

The spans namespace emits caller-defined spans into the same trace waterfall as credential operations. It is available on App, Agent, and constrained sibling clients.

from datetime import UTC, datetime
from alter_sdk import UserSpan
result = await app.spans.emit(
[
UserSpan(
trace_id="trace-123",
name="plan",
start_time=datetime.now(UTC),
attributes={"stage": "planning"},
),
],
)
print(result.accepted)
async def emit(spans: Sequence[UserSpan]) -> EmitSpansResult

Each batch must contain 1–50 UserSpan objects. trace_id, name, and start_time are required. span_id, parent_span_id, end_time, and attributes: dict[str, str] are optional. Supply a stable span_id to make retries idempotent; duplicate (trace_id, span_id) pairs are absorbed and are not included in EmitSpansResult.accepted.

Raises: AlterValueError for an empty or oversized batch or a non-UserSpan item, InsufficientScopeError when the key lacks spans:emit, and BackendError for backend or response-shape failures.

When the application runs an OpenTelemetry SDK with an active span, every call the SDK makes to Alter automatically carries the standard W3C traceparent header — request(), proxy_request(), approval polling, and the audit-reporting calls included. Alter uses it as the trace context for that request’s audit events, and any spans the organization streams to its own OTLP collector join the application’s traces instead of starting disconnected ones.

No configuration is required, and OpenTelemetry is never installed by the SDK itself — it uses whatever OpenTelemetry the application installed. Without OpenTelemetry (or without an active span) the header is simply omitted and nothing changes. The integration is best-effort by design: it can never fail a vault call (the very first call pays a one-time, in-process lookup of the optional module). The optional alter-sdk[otel] extra records the supported opentelemetry-api version range in the application’s dependency tree.

from alter_sdk import PendingApproval
from opentelemetry import trace
tracer = trace.get_tracer("the-application")
# Inside an async function; `app` from the quick start.
with tracer.start_as_current_span("handle-user-request"):
# This call's audit events share the surrounding trace's ids.
response = await app.proxy_request(HttpMethod.GET, url, grant_id=grant_id)
if isinstance(response, PendingApproval):
for gate in response.gates:
print("Approval required:", gate.approval_url)
response = await app.await_approval(response.approval_id)

Only trace/span identifiers and a sampling flag travel in the header — no payloads, no user identifiers.

Sends a large body to the provider with size and SHA-256 verification. Takes path (a file) or data (bytes), plus the addressing, header and audit arguments of proxy_request(). There is no json or body.

from alter_sdk import PendingApproval
result = await app.proxy_upload_request(
"PUT", "https://uploads.example.com/files/report.pdf",
grant_id=grant_id, path="report.pdf",
)
if isinstance(result, PendingApproval):
result = await app.deliver_approved_upload(
str(result.approval_id), path="report.pdf", timeout=3600.0,
)
print(result.status_code)

Returns: ApprovalResult, the provider’s response, or PendingApproval when the call needs approval.

The SDK declares the body’s size and SHA-256 first. Normally policies run on that declaration before bytes reach Alter. For multipart uploads to catalog-declared GraphQL endpoints, Alter first enforces body-independent restrictions (including IP, time, quotas and deny-all rules), then receives and verifies the body in separate bounded encrypted temporary storage, inspects its GraphQL metadata, and evaluates operation/content policies and creates any approval. No bytes reach the provider before those checks pass. If approval is required, deliver the same bytes again after approval; the initial temporary copy is removed. Limits: 50,000,000 bytes per upload, including an upload that needs approval.

  • The provider receives a fixed Content-Length, never chunked framing, and the original bytes, with application/octet-stream by default.
  • Sent once. A failure means calling this again, because a one-shot body is never retried, not even by Alter on a provider’s 421.
  • File contents remain opaque. Registered multipart GraphQL metadata is inspected; other upload bodies are not. A rule that depends on the body refuses the upload with proxy_body_uninspectable, as it does for a binary proxy_request(), and payload capture never includes it. A rule that needs only the operation (an operation allowlist, or an operation match) judges an upload to an operation that takes nothing from its body. A multipart attachment upload is judged by its route only when Alter builds the multipart body (integrations.execute_upload or a provider package); any other multipart body built by the caller and sent with proxy_upload_request() (one that is not a registered GraphQL multipart upload) is refused with proxy_body_uninspectable under any rule that names an operation. The audit record carries the bytes the provider received.
  • Verified at the end. The last 64 KiB are held until the whole body has matched. Bytes that differ from the declaration end the request short of its Content-Length, so the provider cannot read it as a finished body. A provider that acts on a partial request can still see the earlier bytes. Registered GraphQL multipart uploads and calls that need approval do not carry this risk: their bytes are verified in full first.

An upload that stalls for 60 seconds, averages under 10 kB/s, or runs past 15 minutes ends with proxy_upload_timeout. Alter gives a provider up to five minutes to answer once it has the body, but a network edge between the caller and Alter can time out sooner.

Hop-by-hop headers such as Transfer-Encoding and Connection are dropped, as on every proxy call, because Alter sets the framing itself.

Waits for an upload’s approval, sends the approved bytes, and returns the provider’s response.

result = await app.deliver_approved_upload(
approval_id, path="report.pdf", timeout=3600.0, poll_interval=2.0,
)

The approver sees the upload’s size and SHA-256 and that file contents are opaque. For registered GraphQL multipart uploads, the summary also includes the inspected GraphQL metadata, with sensitive inputs masked. Only the API key and agent that requested the approval can deliver it, and delivery must start within one hour of the last approval, after which the approval expires. Alter verifies every byte before contacting the provider. Bytes that do not match are refused with proxy_upload_hash_mismatch and leave the approval open for a correct delivery.

A delivery that sent nothing, because the provider was briefly out of capacity, is refused with proxy_upload_capacity and the approval stays open: deliver again. Once the provider may have received anything, a failure ends the approval failed and the upload needs a new approval. A repeat call after a delivery finished returns its result, so a lost response is not a failure. timeout covers the wait for the decision and then the wait for the result.

Raises: ApprovalDeniedError, ApprovalExpiredError, ApprovalExecutionFailedError, ApprovalTimeoutError, or ProxyTransferError.

Uses the same arguments as proxy_request(), including body: bytes | str.

response = await app.proxy_stream_request(
"GET", "https://api.example.com/export", grant_id=grant_id,
)
async with response:
if response.status_code >= 400: # provider errors are response data, not exceptions
raise RuntimeError(f"Provider answered {response.status_code}")
async for chunk in response.iter_bytes():
await output.write(chunk)

Returns: ProxyStreamResponse.

output is your asynchronous byte sink. Always close the response on early exit.

The request body remains bounded at 5 MiB: use either JSON or raw bytes/UTF-8 text, never both. For a larger body, use proxy_upload_request(). The provider receives the original bytes, with application/octet-stream by default. Binary input is refused with proxy_body_uninspectable when a policy rule needs to read the body (on GraphQL, any operation, family or parameter rule does, unless the provider’s multipart GraphQL body is registered for inspection) and when the call requires approval, because an approver could not see the body. A binary GraphQL body carrying a credential operation or credential-bearing selection is refused with credential_minting_refused. A UTF-8 form or text body on an operation that documents one is the exception: policy reads it from the bytes sent (see Fail-closed). Otherwise the call runs. Payload capture never includes a binary request or that call’s response. A configured AI-review rule also refuses binary input when review is temporarily skipped for entitlement, consent, or availability reasons. This is intentional: changing the body encoding cannot bypass a configured inspection requirement. Use inspectable JSON with that policy.

Streaming responses forward downloads and SSE bytes without base64 or a response size cap. Consume chunks incrementally; collecting them into a list recreates the memory cost in your application. Provider HTTP errors remain response data. Credential-bearing response headers, including cookies and authentication headers, are stripped. Other headers are available on the response object’s headers. Transport failure after headers interrupts iteration; a partially received result is not complete and is never automatically retried.

A provider that sends no headers within the idle deadline raises BackendError with provider_timeout (502). Client-side, iter_bytes() also stops with TimeoutError when a read exceeds the client’s own timeout, which can be shorter than the server’s idle deadline. A stream with a binary body that requires approval is 409 proxy_stream_approval_required.

Defaults are 30 seconds idle and 120 seconds total, with enforced stream admission separate from ordinary calls. ProxyTransferError.code identifies proxy_stream_capacity (503), proxy_stream_timeout (504), proxy_body_uninspectable (422), or proxy_stream_approval_required (409). Approval-gated streaming calls are refused before creating an approval or contacting the provider; use the bounded proxy method for approval-gated requests.

Each admitted provider call consumes policy quota once, as the bounded proxy does. A call counts as one billable request once the provider’s response headers arrive, including provider errors and a caller who disconnects mid-transfer. A connection that never got an answer, and a refusal, are not billed. Streamed payloads are never captured. Terminal audit rows record bytes received and provider-call duration.

The total deadline applies even while bytes are arriving. This method does not support WebSocket upgrades, Set-Cookie, or returned authentication headers.

Streams request uncompressed provider bytes by default. If you explicitly set Accept-Encoding, iteration yields the original encoded bytes; decode them using the returned provider Content-Encoding header.

Alter keeps at most 16 KiB of an uncompressed provider error response transiently for credential-error classification. It never captures this diagnostic body in audit storage. Encoded or larger streamed errors do not automatically mark a credential revoked; their status and bytes still reach the caller unchanged. Downloads and SSE have no diagnostic body buffer.

Report an issue with this page

Necessary

Required for sign-in, security, authorization, and remembering your choices.

Always active

Analytics

Helps us understand how our website, product, and documentation are used.

Performance diagnostics

Uses performance tracing and privacy-masked session replay to diagnose problems.

Advertising

Shares visits and sign-ups with Meta, Reddit, and X so we can measure which of our ads work.

You can change these choices at any time from Cookie settings.