# TypeScript SDK

@affiliaterail/sdk: one typed method for every API operation, with retries, paging and an idempotency key on every POST.

An **SDK** is a library that wraps an API, so you call `ar.partners.list()` instead of building HTTP requests by hand. `@affiliaterail/sdk` is ours for TypeScript and JavaScript. It's made from the [OpenAPI document](/api/clients), so it has one method for each of the 95 merchant operations, and it can't drift from the API.

It isn't on npm yet. Until it is, use it from the repository at `packages/affiliaterail-sdk`. The install line below is what it'll be.

## Use it on a server

Your API key can do everything its scopes allow. Keep it in code that runs on your own server: a script, a job, a backend. Never put it in a browser or a mobile app. Make a key in the app under Settings, then API keys.

```bash
npm install @affiliaterail/sdk
```

## A first run

Use a test key (`rail_test_...`) while you build. It only sees sample data.

```ts
import { AffiliateRail } from "@affiliaterail/sdk"

const ar = new AffiliateRail({ apiKey: process.env.AFFILIATERAIL_API_KEY! })

const programs = await ar.programs.list()
const program_id = programs.data[0]!.id

for await (const partner of ar.partners.listAll({ program_id })) {
  console.log(partner.id)
}

const pending = await ar.commissions.list({ program_id, status: "pending", limit: 10 })
if (pending.data[0]) await ar.commissions.approve(pending.data[0].id)
```

Money is a whole number in the currency's smallest unit, with the currency beside it. For example, 1999 with `usd` is $19.99.

## What it does for you

- **An idempotency key on every POST.** An idempotency key is a unique string sent with a request. If the same request arrives twice, the server does the work once and sends the same answer back. So a retry can't record a second sale or approve a commission twice. Pass your own with `{ idempotencyKey: "payout-run-2026-12-01" }` when your job might run a step twice.
- **Retries.** It tries again after a `429`, a `5xx` or a dropped connection, twice by default. It never retries a delete that may already have run.
- **Paging.** `list` gives one page. `listAll` gives every item and fetches the next page only when your loop asks for it.
- **One error class.** Anything that isn't a success throws `AffiliateRailError`, with `code` to branch on and `requestId` to quote when you ask us for help.

The SDK doesn't ask "are you sure?". `ar.payouts.markPaid(id)` records a payment straight away. If a person should confirm first, put that step in your own code. The [CLI](/api/cli) does ask.

## Method names

A method is named from the path and the HTTP method: `GET /v1/partners` is `ar.partners.list`, `POST /v1/commissions/{id}/approve` is `ar.commissions.approve`, and `POST /v1/payout_batches` is `ar.payoutBatches.create`. The [API reference](/reference) lists every operation. The CLI uses the same words.
