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

# SDK and Code Samples

> Drive the Classet v2 API end-to-end with the typed TypeScript SDK

`@classet/api-client` is a typed, dependency-light wrapper around the [Classet v2 API](/docs/api-reference/overview.md). It's just `fetch` under the hood — it handles `X-API-KEY` auth, the `/v2` path prefix, the `{ data }` / `{ data, meta }` response envelope, per-request timeouts, typed errors, automatic retries that honor `Retry-After`, `Idempotency-Key` propagation, and `X-RateLimit-*` header parsing.

Every example below shows the SDK call and the equivalent raw `curl`, so you can use whichever fits your stack.

## Pilot installation

The SDK is currently available from an authorized Classet monorepo checkout and is not published to npm yet. External package installation will be documented at general availability.

```bash theme={null}
pnpm --filter @classet/api-client build
```

The package is ESM-only and ships its own type declarations — no `@types/*` needed.

## Initialise the client

```ts theme={null}
import { ClassetClient } from '@classet/api-client';

const classet = new ClassetClient({ apiKey: process.env.CLASSET_API_KEY! });
```

`ClassetClient` takes a single options object:

| Option | Type | Default | Notes |
| - | - | - | - |
| `apiKey` | `string` | — | **Required.** Sent as the `X-API-KEY` header. The constructor throws if it's missing. |
| `baseUrl` | `string` | `https://api.classet.ai` | API origin. A trailing slash is trimmed. The `/v2` prefix is added for you. |
| `fetch` | `typeof fetch` | `globalThis.fetch` | Custom fetch for non-global runtimes. |
| `timeoutMs` | `number` | `30000` | Per-attempt timeout in milliseconds (`AbortSignal.timeout`). Timeouts throw and are never retried. |
| `maxRetries` | `number` | `2` | Max retry attempts after the first request. Applies to GETs always; to writes only when an `idempotencyKey` is supplied. |
| `maxRetryAfterMs` | `number` | `60000` | Longest `Retry-After` the client sleeps through. A longer wait throws `ClassetRateLimitError` at once with `retryAfter` set. |

> [!NOTE]
>
> Generate an API key from the [Developer Settings](https://app.classet.ai/settings/developers) page. The same key works on both v1 and v2. Keep it server-side — store it in an environment variable or secrets manager, never in client code.

### Per-request options

Every write method (`create` / `update` / `remove` / `sendInterview` / ...) accepts an optional trailing options object; `timeoutMs` and `maxRetries` also work on the raw transport:

| Option | Effect |
| - | - |
| `idempotencyKey` | Sent as the `Idempotency-Key` header **and** unlocks automatic retries for this write (see [Idempotency](/docs/guides/idempotency.md)) |
| `timeoutMs` | Override the client-level timeout for this request |
| `maxRetries` | Override the client-level retry budget for this request |

### Typed errors

Every method returns the parsed envelope and throws a typed error on a non-2xx response:

* **`ClassetApiError`** — carries `status`, the machine-readable `code`, and `requestId` from the standard `{ error, code, request_id }` envelope (`message` is the `error` string).
* **`ClassetRateLimitError`** — thrown on `429` (extends `ClassetApiError`); adds `retryAfter` (parsed `Retry-After` header, in seconds) and `rateLimit` (parsed `X-RateLimit-*` headers).

```ts theme={null}
import { ClassetApiError, ClassetRateLimitError } from '@classet/api-client';

try {
  const { data: jobs, meta } = await classet.jobs.list({ limit: 20 });
  console.log(`${jobs.length} of ~${meta.total} jobs`);
} catch (err) {
  if (err instanceof ClassetRateLimitError) {
    console.warn(`rate limited — retry in ${err.retryAfter}s`);
  } else if (err instanceof ClassetApiError) {
    console.error(`[${err.code}] ${err.message} (status ${err.status}, request ${err.requestId})`);
  } else {
    throw err; // network failure / timeout
  }
}
```

Branch on `err.code` (stable) rather than the message text — see [Error handling](/docs/guides/error-handling.md#error-codes) for the full code table.

### Automatic retries

Transient failures (`429`, `500`, `502`, `503`, `504`, and network errors) are retried with exponential backoff, honoring the server's `Retry-After` header when present:

* **GETs are retried by default** (up to `maxRetries`, default 2).
* **Writes are retried only when you pass `{ idempotencyKey }`** — without a key the SDK can't know a retry is safe, so it makes exactly one attempt.
* Timeouts and caller aborts are surfaced immediately, never retried.
* A `429` whose `Retry-After` exceeds `maxRetryAfterMs`, or whose body says `exceeded_window: "daily"` or `"monthly"`, throws `ClassetRateLimitError` at once. Check `err.retryAfter` and schedule the retry yourself.
* A `503` is retried only when its `code` is `rate_limit_unavailable` (or the body has no code). `service_unavailable` means the feature is off for your organization, so it is thrown at once.

```ts theme={null}
import { randomUUID } from 'node:crypto';

// Retried automatically on transient failure — never double-created
const { data: ref } = await classet.jobs.create(
  { title: 'HVAC Technician', description: '...', location: { city: 'Austin', region: 'TX', country: 'US', workplace_type: 'onsite' } },
  { idempotencyKey: randomUUID() },
);
```

### Rate-limit visibility

`client.lastRateLimit` exposes the parsed `X-RateLimit-*` headers from the most recent response that carried them, so you can pace proactively:

```ts theme={null}
await classet.candidates.list();
const rl = classet.lastRateLimit;
if (rl?.remaining !== undefined && rl.remaining < 10) {
  console.warn(`only ${rl.remaining}/${rl.limit} requests left until ${rl.reset}`);
}
```

### Iterate whole collections with `listAll`

Paginated resources expose async iterators that walk every page for you:

* `candidates.listAll()` and `applications.listOrgAll()` follow `meta.next_cursor` until it is `null`. Cursor pages do not shift when rows are written mid-walk.
* `jobs.listAll()` and `applications.listAll(jobId)` page by offset and stop on a short page, because those routes take no cursor.

```ts theme={null}
for await (const job of classet.jobs.listAll({ state: 'published' })) {
  console.log(job.job_id, job.title);
}

// Every application in the organization, across all jobs
for await (const app of classet.applications.listOrgAll({ updated_since: '2026-06-01T00:00:00Z' })) {
  console.log(app.id, app.job_id, app.status);
}
```

***

## Create a job

`classet.jobs.create()` posts to `POST /v2/jobs` and returns `{ data: { job_id } }` — the new job's id, not the job itself. Call `classet.jobs.get(job_id)` when you need the full `JobDetail`. `title`, `description`, and `location` are required; everything else is optional.

```ts SDK theme={null}
const { data: job } = await classet.jobs.create({
  title: 'Commercial HVAC Technician',
  description: 'Install and service rooftop units for commercial clients.',
  location: {
    city: 'Austin',
    region: 'TX',
    country: 'US',
    workplace_type: 'onsite',
  },
  wage_lower_bound: 30,
  wage_upper_bound: 45,
  wage_type: 'hourly',
  external_id: 'ats-req-8842', // your own ATS identifier (optional)
});

console.log(job.job_id); // -> use this in later calls
```

```bash curl theme={null}
curl -X POST https://api.classet.ai/v2/jobs \
  -H "X-API-KEY: $CLASSET_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Commercial HVAC Technician",
    "description": "Install and service rooftop units for commercial clients.",
    "location": {
      "city": "Austin",
      "region": "TX",
      "country": "US",
      "workplace_type": "onsite"
    },
    "wage_lower_bound": 30,
    "wage_upper_bound": 45,
    "wage_type": "hourly",
    "external_id": "ats-req-8842"
  }'
```

The response `data` is a `JobRef` (`{ job_id }`) — that `job_id` is what you pass to the candidate, application, and interview calls below. Fetch the rest of the job with `classet.jobs.get(job.job_id)`.

> [!TIP]
>
> Pass `script_id` to attach a specific interview script. Omit it and the job uses your default script. List scripts with `classet.scripts.list()` to find an id.

***

## Create a candidate and send an interview

There are two ways to start an interview. Pick based on whether the candidate already exists.

### One step: create + send

`classet.candidates.create()` posts to `POST /v2/candidates`. Set `send_sms` and/or `send_email` to dispatch the interview invite as part of the same call. `first_name`, `last_name`, and `job_id` are required; `phone` and `email` are optional. The call returns `422` only when `send_sms` or `send_email` asks for a channel the candidate has no contact for (`send_sms` without a phone, `send_email` without an email).

```ts SDK theme={null}
const { data: candidate } = await classet.candidates.create({
  first_name: 'Jordan',
  last_name: 'Rivera',
  email: 'jordan.rivera@example.com',
  phone: '+15125550199',
  job_id: job.job_id,
  send_sms: true,
  send_email: true,
});

console.log(candidate.candidate_id);
```

```bash curl theme={null}
curl -X POST https://api.classet.ai/v2/candidates \
  -H "X-API-KEY: $CLASSET_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Jordan",
    "last_name": "Rivera",
    "email": "jordan.rivera@example.com",
    "phone": "+15125550199",
    "job_id": "'"$JOB_ID"'",
    "send_sms": true,
    "send_email": true
  }'
```

### Two steps: create now, send later

Create the candidate without `send_sms`/`send_email`, then trigger the invite when you're ready with `classet.candidates.sendInterview()` (`POST /v2/candidates/:id/interview`).

```ts SDK theme={null}
const { data: candidate } = await classet.candidates.create({
  first_name: 'Jordan',
  last_name: 'Rivera',
  email: 'jordan.rivera@example.com',
  phone: '+15125550199',
  job_id: job.job_id,
});

// ...later, when you want to start the screen:
await classet.candidates.sendInterview(candidate.candidate_id, {
  send_sms: true,
  send_email: false,
});
```

```bash curl theme={null}
# 1. Create the candidate (no send flags)
curl -X POST https://api.classet.ai/v2/candidates \
  -H "X-API-KEY: $CLASSET_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Jordan",
    "last_name": "Rivera",
    "email": "jordan.rivera@example.com",
    "phone": "+15125550199",
    "job_id": "'"$JOB_ID"'"
  }'

# 2. Send the interview invite later
curl -X POST https://api.classet.ai/v2/candidates/$CANDIDATE_ID/interview \
  -H "X-API-KEY: $CLASSET_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "send_sms": true, "send_email": false }'
```

> [!WARNING]
>
> Interview invites share one budget across the API and dashboard. If your org's invite cap is exhausted, these calls return `429 Interview invite limit exceeded` (the SDK throws a `ClassetRateLimitError` — check `retryAfter`) before any candidate or call record is created for that send. Pass `{ idempotencyKey }` on send calls so a retry can never dispatch the invite twice — see [Idempotency](/docs/guides/idempotency.md).

To halt an in-flight interview, use `classet.candidates.stopInterview(candidateId, { only_stop_outreach })`.

***

## Fetch the aggregated interview

`classet.candidates.getInterview()` (`GET /v2/candidates/:id/interview`) returns one rolled-up `InterviewDetail` — status, outcome, AI summary, extracted custom data, and the recording/transcript — rather than raw per-attempt call rows. This is the call you'll poll (or react to from a webhook) to read results.

```ts SDK theme={null}
const { data: interview } = await classet.candidates.getInterview(
  candidate.candidate_id,
);

console.log(interview.status);   // 'not_sent' | 'in_progress' | 'completed'
console.log(interview.outcome);  // e.g. 'qualified', 'unqualified', null
console.log(interview.summary);  // AI-generated summary, or null
console.log(interview.custom_data);   // extracted variables
console.log(interview.call_count);    // number of attempts
console.log(interview.recording_url); // null until a call completes
```

```bash curl theme={null}
curl https://api.classet.ai/v2/candidates/$CANDIDATE_ID/interview \
  -H "X-API-KEY: $CLASSET_API_KEY"
```

A typed `InterviewDetail` looks like:

```ts theme={null}
interface InterviewDetail {
  candidate_id: string;
  job_id: string | null;
  job_title: string | null;
  status: 'not_sent' | 'in_progress' | 'completed';
  outcome: string | null;
  summary: string | null;
  sent_at: string | null;
  completed_at: string | null;
  question_answers: unknown;
  custom_data: unknown;
  call_count: number;
  recording_url: string | null;
  transcript: unknown;
}
```

> [!NOTE]
>
> Need the raw per-attempt rows (one per call) for debugging? Use `classet.candidates.calls(candidateId)` or `classet.calls.get(callId)`. For everything else, prefer `getInterview` — it's the aggregated view that matches the dashboard.

***

## Configure a webhook

The dark-launch acceptance path uses polling. Any organization with a webhook URL receives [interview events](/docs/guides/webhooks.md#interview-events) (`candidate.interview.updated`); they need no beta admission. [v2 events](/docs/guides/webhooks.md#v2-events-beta) are a separate limited beta, enabled per organization. `classet.webhooks.update()` stores the URL, and `classet.webhooks.test()` verifies reachability; neither action opts your organization into v2 events.

```ts SDK theme={null}
// Point Classet at your receiver
const { data: config } = await classet.webhooks.update({
  event_webhook_url: 'https://your-app.com/webhooks/classet',
});

console.log(config.event_webhook_url);
console.log(config.has_signing_secret); // generate a secret in Developer Settings

// Fire a test delivery at the configured URL
const result = await classet.webhooks.test('event'); // or 'results'
console.log(result.message, result.webhook_url, result.response_status);
```

```bash curl theme={null}
# Register / update the webhook URL
curl -X PUT https://api.classet.ai/v2/webhooks \
  -H "X-API-KEY: $CLASSET_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "event_webhook_url": "https://your-app.com/webhooks/classet" }'

# Send a test delivery
curl -X POST https://api.classet.ai/v2/webhooks/test \
  -H "X-API-KEY: $CLASSET_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "type": "event" }'
```

Read the current configuration any time with `classet.webhooks.get()`. For the event payload shape, signature verification, and retry behaviour, see the [Webhooks guide](/docs/guides/webhooks.md).

***

## Putting it together

A complete create-job → invite-candidate → read-result flow:

```ts theme={null}
import { ClassetClient } from '@classet/api-client';

const classet = new ClassetClient({ apiKey: process.env.CLASSET_API_KEY! });

// 1. Create a job
const { data: job } = await classet.jobs.create({
  title: 'Commercial HVAC Technician',
  description: 'Install and service rooftop units for commercial clients.',
  location: { city: 'Austin', region: 'TX', country: 'US', workplace_type: 'onsite' },
  wage_type: 'hourly',
});

// 2. Create a candidate and dispatch the interview in one call
const { data: candidate } = await classet.candidates.create({
  first_name: 'Jordan',
  last_name: 'Rivera',
  email: 'jordan.rivera@example.com',
  phone: '+15125550199',
  job_id: job.job_id,
  send_sms: true,
  send_email: true,
});

// 3. Read the aggregated result (poll, or react to a webhook instead)
const { data: interview } = await classet.candidates.getInterview(
  candidate.candidate_id,
);

console.log(interview.status, interview.outcome, interview.summary);
```

## Other resource groups

The client covers most of the v2 API. Each group returns the same `{ data }` / `{ data, meta }` envelope:

| Group | Methods |
| - | - |
| `classet.jobs` | `list` · `listAll` · `get` · `stages` · `create` · `update` · `remove` · `applications` |
| `classet.candidates` | `list` · `listAll` · `get` · `create` · `update` · `getInterview` · `sendInterview` · `stopInterview` · `messages` · `calls` |
| `classet.applications` | `listOrg` · `listOrgAll` · `list(jobId)` · `listAll(jobId)` · `get` · `setStage` · `updateStage` · `disqualify` |
| `classet.calls` | `get` (advanced — prefer `candidates.getInterview`) · `downloadRecording` · `recordingUrl` |
| `classet.organization` | `get` |
| `classet.ats` | `listNotes` · `listAttachments` · `listActivity` · `listUsers` · `listBranches` · `listTags` |
| `classet.scripts` | `list` · `get` · `create` · `update` · `remove` · `duplicate` · `addTask` · `updateTask` · `reorderTasks` · `linkAutomation` |
| `classet.knowledge` | `list` · `create` · `update` · `remove` |
| `classet.messageAutomations` | `list` · `get` · `create` · `update` · `remove` · `duplicate` · `setSteps` · `setDefault` |
| `classet.webhooks` | `get` · `update` · `test` |
| `classet.agentSettings` | `get` · `update` |
| `classet.ai` | `generateJob` · `generateScript` · `onboard` |

Org-wide applications and stage moves:

| Method | Endpoint | Use it to |
| - | - | - |
| `applications.listOrg(params)` / `listOrgAll(params)` | [`GET /v2/applications`](/docs/api-reference/applications/list-all-applications) | Sync applications across every job. Filters: `job_id`, `stage`, `outcome`, `source`, `status`, `updated_since`, `created_after`, `created_before`, `cursor` |
| `applications.setStage(id, stage)` | [`PUT /v2/applications/{applicationId}/stage`](/docs/api-reference/applications/move-stage) | Move an application into one of its job's stages. Returns `{ id, stage, previous_stage }`; an unknown stage is a `422` listing the valid names |
| `jobs.stages(jobId)` | [`GET /v2/jobs/{jobId}/stages`](/docs/api-reference/jobs/list-stages) | List the stage names a job accepts, with `meta.source` saying where the list came from |

```ts theme={null}
const { data: stages } = await classet.jobs.stages(job.job_id);
await classet.applications.setStage(applicationId, stages[0].name);
```

These endpoints have no SDK method yet. Call them over HTTP with the same `X-API-KEY` header:

| Endpoint | Use it to |
| - | - |
| [`GET /v2/webhooks/events`](/docs/api-reference/webhooks/list-events) | List outbound webhook deliveries |
| [`GET /v2/webhooks/events/{eventId}`](/docs/api-reference/webhooks/get-event) | Fetch one delivery's signed envelope |

See the [API reference](/docs/api-reference/overview.md) for the full request and response schema of every endpoint, and [Migration from v1](/docs/guides/migration-from-v1.md) if you're upgrading an existing integration.


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