> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apostra.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK guide

> Use the TypeScript and Python SDKs for typed Apostra V3 HTTP calls.

Install `@apostra/sdk` for TypeScript or `apostra` for Python 3.11 or later.
Both packages are generated from the current [V3 OpenAPI 3.1 document](https://docs.apostra.com/v3/http-api.md),
so the generated operation catalogue stays in step with the API. They call HTTP
directly and need no MCP session or LLM. The generated manifest lists
**every public V3 operation**.

For installation and a first campaign preview, see the [SDK quickstart](https://docs.apostra.com/v3/sdk-quickstart.md).

## Make typed calls

```typescript TypeScript theme={null}
import { Apostra } from '@apostra/sdk'

const api = new Apostra()
const status = await api.getStatus()
const delivery = await api.getDelivery({
  report: 'campaign_delivery',
  filters: { campaignId: 'your-campaign-id' },
})
```

```python Python theme={null}
from apostra import Apostra

with Apostra() as api:
    status = api.get_status()
    delivery = api.get_delivery({
        'report': 'campaign_delivery',
        'filters': {'campaignId': 'your-campaign-id'},
    })
```

Python models are typed dictionaries in `apostra.models`. Input field names
remain the wire names. TypeScript exports named `GetDeliveryInput` and
`GetDeliveryResult` types, plus wire models at `@apostra/sdk/models`. Both
languages return the success envelope's `data` directly. Schema patterns,
length limits, conditional requirements and permissions are checked by the API.

For a `campaign_delivery` response with configured campaign or media-buy goals,
`goalProgress` describes the matching goal, commitment, achieved value and
verdict. It is limited to the campaigns and media buys in the current result
page. The V3 response intentionally omits V2-only pacing and denominator
details.

## Inspect a successful response

Each generated method also has a response variant for support and observability
work. TypeScript appends `WithResponse`; Python appends `_with_response`.
These variants keep the normal method's input and write-idempotency rules, and
return the result `data`, request ID and response headers (plus HTTP `status`).
Use the returned request ID to correlate a successful call with support, and
handle headers as potentially sensitive transport metadata rather than logging
them indiscriminately.

```typescript TypeScript theme={null}
const response = await api.getStatusWithResponse()
const requestId = response.requestId
const correlationId = response.headers.get('x-request-id')
```

```python Python theme={null}
response = api.get_status_with_response()
request_id = response['request_id']
correlation_id = response['headers']['x-request-id']
```

## Credentials and accounts

Choose exactly one of an API key, an existing REST/M2M access token, or an
injected token provider. Providers obtain and refresh tokens in your application;
the SDK invokes them for each request and never replays a failed 401 request.
The async Python client uses an async provider. MCP-audience OAuth tokens are
not REST credentials. See [Authentication](https://docs.apostra.com/v3/authentication.md).

For a deployed backend using OAuth client credentials, use the SDK helper with
the client ID, client secret and scope returned when the M2M application was
created. It retains a token only in memory, refreshes it 60 seconds before
expiry, and shares one in-flight refresh between concurrent calls. Keep the
client secret in your server-side secrets manager. Do not use this helper in a
browser or log its inputs or result. Token refreshes have a 30-second deadline
by default; use `timeoutMs` in TypeScript or `timeout` in Python to override it.

```typescript TypeScript theme={null}
const api = new Apostra({
  tokenProvider: m2mTokenProvider({ clientId, clientSecret, scope: 'interchange:read' }),
})
```

```python Python theme={null}
api = Apostra(token_provider=m2m_token_provider(
    client_id=client_id, client_secret=client_secret, scope='interchange:read',
))
```

By default, both SDKs read `APOSTRA_API_KEY`, `APOSTRA_ACCOUNT_ID` and
`APOSTRA_BASE_URL` from the environment. Explicit constructor options override
the environment values. The base URL must use HTTPS, except for a loopback URL
used in local development.

Keep keys on the server. Do not put them in browser bundles, URLs or logs.
Requests send a versioned user agent and name their account with `accountId`
in the request, with no additional telemetry request.

### Credential order

The client picks one credential, in this order:

1. An explicit `apiKey`, `accessToken` or `tokenProvider` option.
2. `APOSTRA_API_KEY` from the environment.
3. The sign-in that `apostra login` stored for the client's base URL. This
   applies in Node.js and Python only when a sign-in exists for that exact base
   URL. Both SDKs read and refresh it without opening a browser. The TypeScript
   SDK exposes `cliLoginTokenProvider({ baseUrl })`; Python exposes
   `cli_login_token_provider(base_url=...)`.

With none of these, the constructor throws. A sign-in is bound to one account.
If you also set `accountId` (Python: `account_id`) or `APOSTRA_ACCOUNT_ID` to a
different account, the constructor throws rather than switching accounts. Both
SDKs store refreshed tokens in the same operating-system credential store as
`apostra login`; see [the CLI](https://docs.apostra.com/v3/cli.md#where-your-sign-in-is-stored). Node.js
and Python processes on the same machine share one refresh lock, so they never
refresh the same token at once. On a machine without a credential store, they
use the CLI's protected 0600-file fallback and warn once rather than silently
writing a plaintext login.

A per-call `accountId` (Python: `account_id`) overrides the client default.
The SDK sends it as `accountId` in the request body, or as the `accountId`
query parameter when reading a write receipt or a document, so it names the account that one
call runs in. The API checks it like any `accountId`: it reaches only accounts
your credential can use, and it does not switch an MCP session or expand
permissions.

An `accountId` already in a call's input names the account that call runs in,
and the SDK sends it as it is. Three inputs were renamed because their
`accountId` named the account being edited or read: `save_account` takes `id`,
a member read on `get` takes `memberAccountId`, and
`save_directed_campaign_subscription` takes `providerAccountId`. If a call to
one of these still passes the old `accountId`, the SDK moves it to the renamed
input and names the client's account itself, so the call reads or edits the
same thing as before. Prefer the renamed inputs in new code. No SDK call sends
the deprecated `X-SCOPE3-CUSTOMER-ID` header, so nothing changes for you when
it retires.

See [Name the account on every call](https://docs.apostra.com/v3/name-the-account.md#the-v3-http-api).

## Errors, retries and cancellation

`ApostraError` exposes HTTP status, `code`, `recovery`, retry timing, and the
request ID. Catch typed errors such as `RateLimitError` and `ValidationError`;
unknown error codes remain strings, so new server codes stay readable.
Malformed responses raise `ProtocolError`; transport failures retain the
underlying fetch/httpx exception. Default exception strings omit response text.

Calls time out after 30 seconds and retry transient network, 429 and 5xx
failures twice by default with full-jitter backoff. Set `maxRetries` (Python:
`max_retries`) to `0` to opt out. Reads retry automatically. Writes replay only
with their required caller-owned idempotency key; the SDK neither generates nor
replaces it. The server's `retry_after` is a minimum delay. Preserve the
operation's original `idempotencyKey`, `clientRequestId` or other
operation-specific key; these fields are not interchangeable.

A `202` raises `InFlightReceiptError` rather than returning a completed result.
It carries the receipt ID, operation, state, pending reason and `Retry-After`
delay. Poll `GET /api/v3/receipts/{receiptId}` with the same credential and
account scope to inspect its current state, or use `settle` (`settle_async` for
async Python) to replay the same keyed operation until it settles, with a
deadline and cancellation. It never creates a replacement key.

TypeScript accepts an `AbortSignal`. Python async calls support task cancellation
and timeouts. Cancelling HTTP does not undo server work. A server mutation must
use the operation's existing state transition if cancellation is supported.
TypeScript timeouts cover token acquisition, HTTP and response-body consumption.
Async Python timeouts cover the awaited provider and HTTP call. A synchronous
Python provider is caller-bounded: a blocked provider raises `TimeoutError`
before dispatch, while httpx uses the same timeout for the HTTP call.

## Pages and asynchronous work

`paginate` (`paginate_async` in async Python) accepts a read callback and a
next-cursor callback. Keep the original query, limit and account fixed. Search
uses `objects.nextCursor`; delivery uses `page.nextCursor`. Delivery pages are
live per call, not a snapshot. Document sections also require the original
`applicability.asOf` value. Cursors are opaque and cannot cross queries.

`poll` accepts a read callback and completion predicate. Python requires a
timeout; TypeScript requires a cancellation signal. For proposal requests,
keep the original body, revision and idempotency key, and distinguish result
pagination from capability pagination. The helper does not choose business
states or retry failed requests.

TypeScript read callbacks receive the helper's cancellation signal. Forward it
to each SDK call so cancellation reaches the HTTP request:

```typescript theme={null}
const signal = AbortSignal.timeout(30_000)
for await (const page of paginate(
  (cursor, signal) => api.search({ kind: 'inventory_source', limit: 20, cursor }, { signal }),
  page => page.objects?.nextCursor,
  signal,
)) {
  // Consume the page without changing the original query or account.
}
```

Python task cancellation propagates into the async helper's awaited read.
Injected providers and transports must cooperate to stop their underlying work.

## Wait for a person to act

Some results ask a person to act in a browser before the work can continue.
V3 says so in one of two ways:

* a `humanHandoff` field: a link bound to one account, with an expiry and a
  `resume` rule that says how to tell the step is done;
* `action: "approval_required"`: the request is recorded and runs only after a
  signed-in administrator approves it on the Apostra site
  ([Approving agent requests](https://docs.apostra.com/v2/concepts/web-approvals.md)).

`findHandoff` / `find_handoff` recognises either shape in any operation's
result. It returns one handoff, or `null` / `None` when the result asks nothing
of a person. A handoff carries:

* `url`, the link to show the person. It is sensitive: do not log or post it.
* `account`, the account the step is bound to (`id`, and `name` where the
  result gives one; an approval gives only the id).
* `action`, the handoff action, or the approval kind such as `iu_plan.accept`.
* `expiresAt` (`expires_at` in Python) and `resume`.

`open(opener?)` opens the link only when you call it, and only through the
opener you pass. Without an opener it returns the URL, so headless code can
print it. The SDK never opens a browser by itself.

`waitForCompletion` / `wait_for_completion` (`wait_for_completion_async` in
async Python) waits until a fresh read from the server shows the step is done,
then returns that read. A browser opening or closing never counts as done.

| Handoff | The fresh read | Done when |
| - | - | - |
| Approval (`resume.kind: "approval"`) | Your `read`: the original call repeated with the same body and the same idempotency key | By default, the result is no longer a `pending` or `executing` approval |
| Connection (`resume.kind: "connection"`) | Pass `client` to read the connection with `get` (`kind: "connection"`) in the handoff's account, or pass your own `read` | Your `until` |
| Page (`resume.kind: "manual"`) | Your `read` of the object the Page changes | Your `until` |

Once an approval is final, the repeated call returns the operation's normal
result, or an `approval_required` result whose `approval.state` is `rejected`,
`expired` or `failed`. Check the returned value: the SDK does not turn those
states into errors. A write that is still in flight (HTTP 202) counts as not
done yet. Pass `timeoutMs` (`timeout`, in seconds, in Python); reads repeat
every 5 seconds unless you set `intervalMs` / `interval`. So that one slow read
cannot outlast the wait, TypeScript passes `read` a cancellation signal and
synchronous Python passes it the seconds left: forward them to the SDK call
(`signal`, or `timeout`). A timeout or cancellation stops the wait, not the
person's step.

```typescript TypeScript theme={null}
import { Apostra, findHandoff } from '@apostra/sdk'

const api = new Apostra()
const idempotencyKey = 'choose-plan-2026-11'
const input = { plan: { offerVersion, planId, idempotencyKey } }
const result = await api.saveBilling(input, { idempotencyKey })

const handoff = findHandoff(result)
if (handoff) {
  // Show the person the account, the action and the link in your own UI. Never
  // write the link to a log. Call handoff.open(opener) only if they ask.
  showToPerson(handoff.account, handoff.action, handoff.url)
  const final = await handoff.waitForCompletion({
    read: (signal) => api.saveBilling(input, { idempotencyKey, signal }),
    timeoutMs: 30 * 60_000,
  })
}
```

```python Python theme={null}
from apostra import Apostra, find_handoff

with Apostra() as api:
    key = 'choose-plan-2026-11'
    request = {'plan': {'offerVersion': offer_version, 'planId': plan_id, 'idempotencyKey': key}}
    result = api.save_billing(request, idempotency_key=key)

    handoff = find_handoff(result)
    if handoff:
        # Show the person the account, the action and the link in your own UI.
        # Never write the link to a log. Call handoff.open(opener) only if they ask.
        show_to_person(handoff.account, handoff.action, handoff.url)
        final = handoff.wait_for_completion(
            read=lambda left: api.save_billing(request, idempotency_key=key, timeout=left),
            timeout=30 * 60,
        )
```

## Human steps and unsupported helpers

`uploadCreativeAsset` / `upload_creative_asset` returns the typed current human
task and `fallback_url`. Some UI results expose optional `openInBrowserUrl`;
others expose parameters only. The SDK never invents a URL from those parameters.

Import TypeScript `verifyWebhook` from the server-only
`@apostra/sdk/webhooks` subpath; it does not load into the browser-safe SDK root.
`verifyWebhook` / `verify_webhook` verifies the raw V3 webhook body with
duplicate-preserving signature, timestamp, and delivery-ID headers. It rejects
duplicate headers, uses constant-time HMAC comparison, enforces the five-minute
window, and selects the secret by key ID so callers can keep both rotation keys.

`openHandoff` / `open_handoff` returns an actual HTTPS URL supplied by the
caller. It opens nothing in headless code. Interactive applications can inject
an opener. `getHandoff` / `get_handoff` narrows a result to a Page handoff
(`kind`, `url`, `expiresAt`, `resume`) or returns `null` / `None`; prefer
`findHandoff` / `find_handoff`, which also recognises approvals and can wait
([Wait for a person to act](https://docs.apostra.com/v3/sdk-guide.md#wait-for-a-person-to-act)). There is no embedded
UI, OAuth login flow or byte-upload helper in the current SDK contract; those
need a public contract before they can be supported. The SDK never constructs
a URL.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.