# TypeScript SDK

The @askads/sdk package is a small typed client for the AskAds API, with no runtime dependencies. It runs on Node 18.17 and up, and on Bun.

## Install

```bash
npm install @askads/sdk
```

## Use

```ts
import { AskAds } from '@askads/sdk';

const askads = new AskAds({ apiKey: process.env.ASKADS_API_KEY });

const me = await askads.getMe();
const { data: accounts } = await askads.listAdAccounts();
const report = await askads.getPerformanceReport({ adAccountId: accounts[0].id, period: 'last_7_days' });

const draft = await askads.createDraftCampaign({
  adAccountId: accounts[0].id,
  name: 'Spring launch',
  objective: 'traffic',
  dailyBudget: 30,
  audience: { countries: ['US'] },
  ads: [{ name: 'Spring 1', headline: 'Fresh roast, delivered', primaryText: 'Our spring blend is here.', callToAction: 'shop_now', destinationUrl: 'https://sunrise.example/spring' }],
});

const asked = await askads.proposeLaunch({ adAccountId: accounts[0].id, level: 'campaign', id: draft.campaignId });
console.log('A person approves here:', asked.approvalRequest.approveUrl);
```

There is one method per operation, named like the `operationId` in the [API reference](/developers/api). There is no approve method, because the API has none.

## Options

| Option | Default | What it does |
|---|---|---|
| `apiKey` | `ASKADS_API_KEY` from the environment | An `ask_key_` key or an `ask_cli_` login. |
| `baseUrl` | `https://askads.app` (or `ASKADS_BASE_URL`) | `/api/v1` is added for you. Plain `http` only for localhost. |
| `maxRetries` | 2 | Retries after a 429, a 5xx or a network error, waiting for `Retry-After`. |
| `timeoutMs` | 60 seconds | Per try. |
| `fetch` | the global fetch | Your own, for tests or a proxy. |

## Built in

- **Idempotency**: every write gets an `Idempotency-Key`, reused on each retry, so a retry after a lost answer never runs twice. Pass your own with `{ idempotencyKey: '...' }` as the second argument.
- **Paging**: list methods return one page `{ data, hasMore, nextCursor }`. `askads.paginate('listCampaigns', { adAccountId })` walks every page for you.
- **Errors**: a failed call throws an `AskAdsError` with `status`, `type`, `code`, `param`, `requestId` and `docUrl`. Subclasses by type: `PermissionError`, `SpendingLimitError`, `RateLimitError`, `NotFoundError` and so on. Branch on `error.code` (see [errors](/developers/errors)).
- **Webhooks**: `verifyWebhook(rawBody, header, secret)` returns true or false; `constructWebhookEvent(rawBody, header, secret)` returns the parsed event or throws `WebhookSignatureError`.

```ts
import { constructWebhookEvent } from '@askads/sdk';

const event = constructWebhookEvent(rawBody, request.headers.get('AskAds-Signature'), process.env.ASKADS_WEBHOOK_SECRET!);
if (event.type === 'approval.approved') { /* ... */ }
```
