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

# Client libraries for TypeScript and Python

> Install the Elastly client for TypeScript or Python, authenticate with an API key, call an endpoint, handle errors and use the TypeScript helpers.

Elastly publishes a client for TypeScript and a client for Python. Both are generated from the same API document as the [API reference](/docs/api-reference/introduction.md), so every endpoint, field and error code in the reference is available with types. This page covers installing a client, making a first request, handling errors and the three helpers in the TypeScript package.

For any other language, call the API over HTTPS as the guides show, or generate a client from the [API document](/docs/api-reference/introduction.md).

## Install

```bash TypeScript theme={null}
npm install @elastly/node
```

```bash Python theme={null}
pip install elastly
```

The TypeScript package needs Node.js 20 or later. The Python package needs Python 3.11 or later.

## Create a client

Create one client with your API key and reuse it. See [Authentication](/docs/developers/authentication.md) for the key types.

```typescript TypeScript theme={null}
import { createElastly } from "@elastly/node"

const elastly = createElastly({ apiKey: process.env.ELASTLY_API_KEY })
```

```python Python theme={null}
import os

from elastly import AuthenticatedClient

client = AuthenticatedClient(
    base_url="https://api.elastly.ai",
    token=os.environ["ELASTLY_API_KEY"],
)
```

## Make a request

Each endpoint in the API reference is one method in TypeScript and one module in Python, named after the operation.

```typescript TypeScript theme={null}
import { answerOf } from "@elastly/node"

const priced = answerOf(
  await elastly.price({
    body: {
      buyer: { kind: "customer", customerRef: "CUST-2207" },
      currency: "USD",
      lines: [{ sku: "6205-2RS", quantity: "400" }],
    },
  }),
)
```

```python Python theme={null}
from elastly.api.default import price
from elastly.models import PriceBody

priced = price.sync(
    client=client,
    body=PriceBody.from_dict(
        {
            "buyer": {"kind": "customer", "customerRef": "CUST-2207"},
            "currency": "USD",
            "lines": [{"sku": "6205-2RS", "quantity": "400"}],
        }
    ),
)
```

In Python, every operation has four forms: `sync` and `asyncio` return the parsed body, and `sync_detailed` and `asyncio_detailed` return the status, headers and parsed body together.

## API version

A client sends the API version it was generated from in the `Elastly-Version` header on every request, so a request never depends on the version pinned on the key. To call another version, pass `apiVersion` to `createElastly` in TypeScript or `elastly_version` to an operation in Python. See [Versioning](/docs/developers/versioning.md).

## Handle errors

In TypeScript, a method resolves with `data`, `error` and `response`. `answerOf` returns the body of a successful response and throws for anything else.

| Thrown | When | Fields |
| - | - | - |
| `ElastlyApiError` | The API answered with an error | `status`, `code` and `requestId` |
| `ElastlyConnectionError` | The API could not be reached or the request was aborted | `cause` |

`code` is the error code from [Errors](/docs/developers/errors.md).

```typescript TypeScript theme={null}
import { answerOf, ElastlyApiError } from "@elastly/node"

try {
  answerOf(await elastly.getDecision({ path: { id: decisionId } }))
} catch (error) {
  if (error instanceof ElastlyApiError && error.code === "not_found") {
    // no decision with this ID
  }
}
```

In Python, an operation returns the parsed success body or an `ApiError` with `error` and `request_id`.

## Idempotency keys

Endpoints that need an `Idempotency-Key` take it as a required header in TypeScript and a required `idempotency_key` argument in Python. See [Idempotency](/docs/developers/idempotency.md).

## TypeScript helpers

The TypeScript package adds three helpers on top of the generated client.

### Verify a webhook

`verifyWebhook` checks the signature and the age of a delivery and returns the typed event. Pass the request body exactly as received. It throws `WebhookVerificationError` with a `code` of `missing_header`, `timestamp_out_of_tolerance`, `signature_mismatch` or `invalid_payload`.

```typescript TypeScript theme={null}
import { verifyWebhook } from "@elastly/node"

const event = verifyWebhook({
  secret: webhookSecret,
  headers: request.headers,
  body: rawBody,
})
```

`webhookSecret` is the endpoint's signing secret, which starts with `whsec_`. A delivery older than five minutes is refused. Set `toleranceSeconds` to change that. See [Webhooks and events](/docs/developers/webhooks.md).

### Apply queued prices

`drainWriteback` claims queued prices, calls your `apply` function for each one, keeps the lease alive while `apply` runs and reports every result in one request. It runs until you abort its signal. See [Write-back queue](/docs/developers/writeback-queue.md).

```typescript TypeScript theme={null}
import { drainWriteback } from "@elastly/node"

await drainWriteback({
  client: elastly,
  signal: shutdown.signal,
  apply: async (item) => {
    await erp.setPrice(item.product.sku, item.price, item.currency)
    return { outcome: "applied" }
  },
})
```

Return `{ outcome: "rejected", code, message }` for a price your system will never accept and `{ outcome: "retry" }` to try again later. If `apply` throws, the item is reported as `retry` with the error message.

### Keep serving prices during an outage

`createFailOpenPricing` remembers the last successful response for each request. When the API cannot be reached, does not answer within the timeout or answers with a `5xx` status, it returns the remembered response with `stale: true`. A remembered line is served only until its `validUntil`; after that the line is left out and the call fails if no line remains.

```typescript TypeScript theme={null}
import { createFailOpenPricing } from "@elastly/node"

const prices = createFailOpenPricing({ client: elastly })

const { response, stale } = await prices.price({
  buyer: { kind: "customer", customerRef: "CUST-2207" },
  currency: "USD",
  lines: [{ sku: "6205-2RS", quantity: "400" }],
})
```

| Option | Default | Meaning |
| - | - | - |
| `timeoutMs` | `2000` | How long to wait for the API before using the remembered response |
| `maxStaleMs` | none | An optional extra limit on the age of a remembered response. Without it, each line's `validUntil` alone decides |
| `maxEntries` | `10000` | How many requests are remembered |

A remembered response is served only for the same buyer, currency and lines. A request the API refuses, such as `invalid_request` or `insufficient_scope`, is never answered from memory. Responses are kept in the memory of the process and are lost when it restarts.

> [card] [Price requests](/docs/developers/price-requests.md)
>
> Price lines and quotes, report outcomes and read decisions.

> [card] [Write-back queue](/docs/developers/writeback-queue.md)
>
> Claim approved prices and report the result of each one.


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