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

# Error Handling

> HTTP status codes, error response shapes, and retry/backoff strategy for the v2 API

Every v2 endpoint returns a conventional HTTP status code and a JSON body describing what went wrong. This guide covers the error envelope, the machine-readable `code` values, the status codes you'll see, and how to retry transient failures safely.

## The error envelope

Every error response uses the same three-field envelope:

```json theme={null}
{
  "error": "Candidate not found",
  "code": "not_found",
  "request_id": "9f6a2c1e-4b3d-4a8e-9f2a-7c1d0e5b6a3f"
}
```

| Field | Type | Description |
| - | - | - |
| `error` | string | Short, human-readable summary — safe to surface or log |
| `code` | string | Stable machine-readable error code (table below). **Branch on this**, not on the `error` text, which may change |
| `request_id` | string | Correlates to the `X-Request-Id` response header — quote it to support |

Internal details — Postgres/PostgREST driver messages, constraint names, column hints — are **never** included; they're logged server-side and masked from the response.

Some statuses merge extra fields **on top of** the envelope — most importantly `429` (see [Rate limits and send caps](#429-rate-limits-and-send-caps)), `402` (`reason`) and some `409`s.

> [!NOTE]
>
> Success responses use a different envelope: single objects return `{ "data": {...} }` and lists return `{ "data": [...], "meta": { "page", "limit", "total" } }`. See [Migration from v1](/docs/guides/migration-from-v1.md#response-envelope).

## Error codes

The `code` field takes exactly one of these values:

| `code` | Typical status | Meaning |
| - | - | - |
| `bad_request` | `400` | The request can't be processed as sent — malformed header, invalid state transition |
| `validation_error` | `400` | Automatic schema validation failed — a field is missing, mistyped, or out of bounds |
| `unauthorized` | `401` | No API key supplied |
| `quota_exceeded` | `402` | The organization's free-trial interview allowance is spent. The body carries a `reason` field |
| `forbidden` | `403` | API key invalid/inactive, or the organization isn't entitled to what the request asks for (a language or AI screening it doesn't have) |
| `not_found` | `404` | Resource doesn't exist, or belongs to another org |
| `conflict` | `409` | Duplicate, state precondition not met, or a concurrent idempotent request in flight |
| `request_in_progress` | `409` | Another request for the same person on the same job is running. Wait for `Retry-After` and send it again |
| `recently_contacted` | `409` | The phone number or email this request would reach was already contacted for this job in the last 12 hours through another candidate record. Nothing was created or sent; `data.candidate_id` is that candidate and `data.retry_at` is when a send is accepted again |
| `payload_too_large` | `413` | The request body is over 1 MiB. Send resumes as a URL, not inline |
| `unprocessable` | `422` | The request is well-formed but semantically invalid (e.g. neither `send_sms` nor `send_email` set) |
| `rate_limited` | `429` | Request rate limit or interview-invite cap exceeded |
| `rate_limit_unavailable` | `503` | The invite rate limiter is temporarily unreachable — retry shortly |
| `service_unavailable` | `503` / `502` | `503`: external sends and writes aren't enabled for this organization. `502`: the connected ATS rejected or failed a disqualify |
| `internal_error` | `5xx` | Something failed on our side |

## Status codes at a glance

| Status | `code` | Meaning | Retry? |
| - | - | - | - |
| `400` | `validation_error` / `bad_request` | Validation failed — bad/missing field, malformed request | No — fix the request |
| `401` | `unauthorized` | No API key supplied | No — add `X-API-KEY` |
| `402` | `quota_exceeded` | Free-trial interview allowance spent | No — upgrade the plan or contact [success@classet.ai](mailto:success@classet.ai) |
| `403` | `forbidden` | Invalid/inactive key, or an entitlement the organization doesn't have | No — check the key or the organization's plan |
| `404` | `not_found` | Resource not found, or not in your org | No |
| `409` | `conflict` | Duplicate, state precondition, or concurrent idempotency key | Only for an in-flight idempotency key — see [409](#409-conflict) |
| `422` | `unprocessable` | Well-formed but semantically invalid | No — fix the request |
| `429` | `rate_limited` | Rate limit or interview-send cap exceeded | **Yes** — honor `Retry-After` |
| `503` | `rate_limit_unavailable` | Invite rate limiter unavailable | **Yes** — honor `Retry-After` |
| `503` | `service_unavailable` | `External API mutations are not enabled for this organization` | No — permanent until Classet enables sends for your organization |
| `502` | `service_unavailable` | Upstream ATS failure on `POST /v2/applications/{id}/disqualify` | Once, after a short wait |
| `5xx` | `internal_error` | Server/database error | **Yes** — backoff, use an idempotency key on writes |

The retryable cases are `429`, `503 rate_limit_unavailable`, `500` and `504`, and a `502` that isn't `service_unavailable`. Retry a `502 service_unavailable` once, and a `409` only when the idempotency key is still in flight. Two `503`s share a status but not a remedy, so **branch on `code`, not on the status**: `rate_limit_unavailable` clears on its own, while `service_unavailable` is a setting on your organization and every retry fails the same way. Everything else in the `4xx` range is a client error — retrying without changing the request will fail the same way.

***

## 400 Bad request

There are two flavors of `400`, distinguished by `code` — both use the standard envelope.

### Automatic schema validation (`validation_error`)

Request body, query, param, and header validation is generated from each route's Zod/OpenAPI schema. When validation fails, the failing fields are summarized into the `error` string as semicolon-separated `path: message` pairs (capped at the first 10 issues):

```json theme={null}
{
  "error": "name: Invalid input: expected string, received undefined; location.city: Required",
  "code": "validation_error",
  "request_id": "9f6a2c1e-4b3d-4a8e-9f2a-7c1d0e5b6a3f"
}
```

The path segment before each `: ` names the offending field (dot-notation for nested fields, `(root)` for top-level issues). There is no separate structured issues array — the summary string is the contract.

### Business-rule failures (`bad_request`)

Checks that can't be expressed in the schema (state checks, malformed headers) return `bad_request` with a specific message, for example:

```json theme={null}
{
  "error": "The AI interview flow is already initiated for this candidate",
  "code": "bad_request",
  "request_id": "9f6a2c1e-4b3d-4a8e-9f2a-7c1d0e5b6a3f"
}
```

An `Idempotency-Key` header outside the allowed 1–255 character range is also a `400 bad_request` — see the [Idempotency guide](/docs/guides/idempotency.md).

> [!TIP]
>
> Branch on `code`: `validation_error` means a field in your request doesn't match the schema (the `error` string tells you which); `bad_request` means the request was understood but can't be performed in the current state.

***

## 401 Unauthorized

No API key was supplied — the `X-API-KEY` header is missing entirely.

```json theme={null}
{
  "error": "No API key provided",
  "code": "unauthorized",
  "request_id": "9f6a2c1e-4b3d-4a8e-9f2a-7c1d0e5b6a3f"
}
```

Pass your key on every request:

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

The only unauthenticated routes are `GET /v2/health`, `GET /v2/openapi.json`, and `GET /v2/docs`.

## 402 Payment required

Endpoints that start an interview — `POST /v2/candidates` with `send_sms`/`send_email`, `POST /v2/candidates/{id}/interview`, and the deprecated `POST /v2/calls` — check the organization's free-trial interview allowance first. When it's spent, the send is refused with `402` and nothing is queued:

```json theme={null}
{
  "error": "Interview not initiated: free trial <reason>",
  "code": "quota_exceeded",
  "request_id": "9f6a2c1e-4b3d-4a8e-9f2a-7c1d0e5b6a3f",
  "reason": "<reason>"
}
```

`reason` says why the allowance is spent. Don't retry — the allowance doesn't refill on a timer. Upgrade the plan or contact Classet.

## 403 Forbidden

`403` means a key was sent but the request isn't allowed. There are two causes.

The key didn't resolve to an active organization — it's wrong, revoked, or inactive:

```json theme={null}
{ "error": "Invalid API key", "code": "forbidden", "request_id": "..." }
```

Or the organization isn't entitled to what the request asks for. Creating or updating a job returns `403` when it adds a language the organization hasn't enabled (`Language not enabled for this organization`), or turns on AI screening without a plan that includes it (`AI screening entitlement required`).

`401` means "you sent nothing," `403` means "what you sent isn't allowed." Neither should be retried. For a key error, verify the key in [Developer Settings](https://app.classet.ai/settings/developers). For an entitlement error, change the request or the organization's plan.

## 404 Not found

The resource doesn't exist **or** belongs to another organization. The v2 API scopes every query to the org behind your API key, so a resource owned by a different org is indistinguishable from one that doesn't exist — both return `404`.

```json theme={null}
{ "error": "Candidate not found", "code": "not_found", "request_id": "..." }
```

Unknown routes (a typo in the path, a missing `/v2` prefix) also return a JSON `404 not_found` — never an HTML error page.

## 409 Conflict

The request collides with current state. Three common cases:

A duplicate would be created:

```json theme={null}
{
  "error": "Candidate already exists for this email or phone on this job. Set force_create to true to create a new candidate anyway.",
  "code": "conflict",
  "request_id": "...",
  "data": { "candidate_id": "...", "webcall_url": "...", "interview_panel_url": "..." }
}
```

A state precondition isn't met. Some `409`s include an extra context field alongside the envelope:

```json theme={null}
{
  "error": "Interview outcome already determined",
  "code": "conflict",
  "request_id": "...",
  "interview_outcome": "qualified"
}
```

A request with the same `Idempotency-Key` is still in flight:

```json theme={null}
{
  "error": "A request with this Idempotency-Key is already in progress",
  "code": "conflict",
  "request_id": "9f6a2c1e-4b3d-4a8e-9f2a-7c1d0e5b6a3f"
}
```

For the first two, re-check state (e.g. fetch the candidate) before retrying rather than blindly resending. For the in-flight idempotency conflict, wait briefly and retry with the **same** key — once the original completes, the retry replays its response. See the [Idempotency guide](/docs/guides/idempotency.md).

> [!WARNING]
>
> All three cases share `code: "conflict"`, but only the in-flight idempotency key is worth retrying — a duplicate candidate is permanent. Until a distinct code ships, tell them apart by the `error` text: retry only when it contains `already in progress`. This text match is a stopgap; when the in-flight case gets its own `code`, it will be announced in the [changelog](/docs/changelog.md), and you should switch to it.

## 422 Unprocessable

The request parses and validates against the schema, but is semantically invalid — you asked for something that can't be done as specified. For example, sending an interview with neither channel enabled:

```json theme={null}
{
  "error": "Either send_sms or send_email must be true",
  "code": "unprocessable",
  "request_id": "..."
}
```

Fix the request; retrying unchanged will fail the same way.

***

## 429 Rate limits and send caps

`429` is a status you **should** retry, but the body comes in a few shapes depending on which limit you hit. All of them carry `code: "rate_limited"` on top of the standard envelope and set a `Retry-After` response header (in seconds) where applicable.

### Interview invite cap (send endpoints)

Endpoints that send an interview invite — `POST /v2/candidates` (with `send_sms`/`send_email`), `POST /v2/candidates/:id/interview`, and the deprecated `POST /v2/calls` — share one invite budget across the API and the dashboard. The budget is enforced across four windows: per-minute (`burst`), per-hour (`sustained`), `daily`, and `monthly`. When a send would exceed a window, the request is rejected **before** any candidate/call record is created:

```json theme={null}
{
  "error": "Interview invite limit exceeded",
  "code": "rate_limited",
  "request_id": "9f6a2c1e-4b3d-4a8e-9f2a-7c1d0e5b6a3f",
  "message": "This interview invite would exceed your per-hour send limit of 1000. You've already used your full per-hour allowance. This limit resets every hour. Need a higher limit? Contact Classet support.",
  "exceeded_window": "sustained",
  "limit": 1000,
  "retry_at": "2026-06-25T18:00:00.000Z"
}
```

| Field | Type | Description |
| - | - | - |
| `error` | string | Always `Interview invite limit exceeded` |
| `code` | string | Always `rate_limited` |
| `message` | string | Human-readable detail, including which window and when it resets |
| `exceeded_window` | string | The window that tripped: `burst`, `sustained`, `daily`, or `monthly` |
| `limit` | number | The cap for that window |
| `retry_at` | string \| undefined | ISO 8601 timestamp when the window resets |

The `Retry-After` header (seconds until `retry_at`) is set on this response — prefer it over parsing `retry_at` yourself.

### Request rate limit

A separate per-org request-rate limiter (when enabled) guards overall throughput:

```json theme={null}
{
  "error": "Rate limit exceeded",
  "code": "rate_limited",
  "request_id": "9f6a2c1e-4b3d-4a8e-9f2a-7c1d0e5b6a3f",
  "message": "You have exceeded your rate limit of 1000 requests per hour",
  "retry_after": 1820,
  "limit": 1000,
  "remaining": 0,
  "reset_at": "2026-06-25T18:00:00.000Z"
}
```

This response also sets `Retry-After` plus the standard `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`, and `X-RateLimit-Used` headers, which are present on successful requests too — read them to pace yourself before you ever hit a `429`. See [Rate limits](/docs/guides/rate-limits.md) for the full header semantics, including `X-RateLimit-Degraded`.

> [!WARNING]
>
> Don't hard-code which window or limiter produced a `429`. Branch on the presence of fields (`exceeded_window` vs `retry_after`) and always fall back to the `Retry-After` header for timing.

***

## 503 Rate limiter unavailable

On the invite-sending endpoints, the invite budget **fails closed**: if the rate-limit backend is unreachable, the send is rejected rather than silently bypassing your caps. You get a `503` with `code: "rate_limit_unavailable"` and a `Retry-After` header:

```json theme={null}
{
  "error": "Invite rate limiting is temporarily unavailable",
  "code": "rate_limit_unavailable",
  "request_id": "9f6a2c1e-4b3d-4a8e-9f2a-7c1d0e5b6a3f"
}
```

No invite slot is consumed and no candidate/call record is created — the request had no effect, so it's always safe to retry after `Retry-After` seconds. This is a transient infrastructure condition, not a limit you exceeded.

## 503 / 502 Service unavailable

`code: "service_unavailable"` covers two different conditions. Neither is the transient `503` above, so don't let a status-only retry loop pick them up.

**`503` — sends and writes aren't enabled for your organization.** Endpoints that reach outside Classet (sending an interview, stopping an interview, attaching a resume by URL, disqualifying in the ATS, sending a test webhook) check a per-organization switch first:

```json theme={null}
{
  "error": "External API mutations are not enabled for this organization",
  "code": "service_unavailable",
  "request_id": "9f6a2c1e-4b3d-4a8e-9f2a-7c1d0e5b6a3f"
}
```

This is permanent until Classet turns sends on for your organization. Retrying won't help — ask Classet to enable them.

**`502` — the connected ATS failed a disqualify.** `POST /v2/applications/{id}/disqualify` writes through to your ATS. When the ATS rejects or fails the write, the API returns `502` with the ATS's message in `error`. It may be a transient upstream failure, so retry once after a short wait; if it fails again, treat it as permanent and check the application in the ATS.

***

## 5xx Server errors

A `5xx` means something failed on our side — typically a database error. The driver message is logged server-side and masked from you:

```json theme={null}
{
  "error": "Operation failed: list_candidates",
  "code": "internal_error",
  "request_id": "9f6a2c1e-4b3d-4a8e-9f2a-7c1d0e5b6a3f"
}
```

These are transient by nature. Retry with backoff (below). Every response carries an `X-Request-Id` header (matching the body's `request_id`) — include it when contacting [support](mailto:success@classet.ai) so we can correlate it to our logs.

***

## Retrying transient failures

Retry `429`; `503` with `code: "rate_limit_unavailable"`; `500` and `504`; a `502` whose `code` isn't `service_unavailable` (gateway errors can arrive with no `code` at all); `502 service_unavailable` once; and a `409` whose `error` says the idempotency key is `already in progress`. Read the `code` before you retry a `502` or `503`: `503 service_unavailable` is permanent. Honor the `Retry-After` header (seconds) when present; otherwise fall back to exponential backoff with jitter. Never retry other `4xx` responses — they won't succeed without a different request.

**Never blind-retry `POST /v2/onboard`.** It is the exception to the `500` rule. An AI provider failure partway through returns `500` and can leave the jobs and knowledge entries it already created, and an `Idempotency-Key` doesn't help because a `5xx` is never cached. Keep it out of any generic retry loop; check `GET /v2/jobs` and `GET /v2/knowledge` and clean up before retrying by hand. See [Onboard Company](/docs/api-reference/ai/onboard.md).

**Retrying writes safely.** A `5xx` on a `POST` can leave you unsure whether the request took effect. Send an [`Idempotency-Key` header](/docs/guides/idempotency) on every `POST` you might retry: a `5xx` outcome is never cached, so the retry re-executes the request cleanly, while a retry of a request that actually succeeded replays the original response instead of acting twice. The [TypeScript SDK](/docs/guides/sdk-and-code-samples.md) does all of this for you — it retries GETs automatically and retries writes when you pass `{ idempotencyKey }`.

```typescript fetch (Node 18+ / browser) theme={null}
const RETRYABLE = new Set([409, 429, 500, 502, 503, 504]);

interface RetryOptions {
  maxRetries?: number;   // default 4
  baseDelayMs?: number;  // default 500
  maxDelayMs?: number;   // default 20_000
}

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

/**
 * Fetch with retry/backoff for transient Classet API failures (429, 5xx and
 * the in-flight idempotency 409).
 * Respects the `Retry-After` header; otherwise uses exponential backoff
 * with full jitter. Other 4xx are returned immediately.
 * Pass an Idempotency-Key header on POSTs so retries can't double-apply.
 */
export async function classetFetch(
  url: string,
  init: RequestInit = {},
  opts: RetryOptions = {}
): Promise<Response> {
  const { maxRetries = 4, baseDelayMs = 500, maxDelayMs = 20_000 } = opts;

  const headers = {
    "X-API-KEY": process.env.CLASSET_API_KEY!,
    "Content-Type": "application/json",
    ...init.headers,
  };

  let lastRes: Response | undefined;
  let atsRetried = false; // 502 service_unavailable gets one retry

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    let res: Response;
    try {
      res = await fetch(url, { ...init, headers });
    } catch (err) {
      // Network-level failure — treat as transient.
      if (attempt === maxRetries) throw err;
      await sleep(backoff(attempt, baseDelayMs, maxDelayMs));
      continue;
    }

    if (!RETRYABLE.has(res.status)) return res; // success or non-retryable 4xx
    const body = await res.clone().json().catch(() => null);
    // 409 is also a duplicate candidate, which never clears. Retry only the
    // in-flight idempotency key (text match until a distinct code ships).
    if (res.status === 409 && !String(body?.error ?? "").includes("already in progress")) return res;
    // Branch on code, not status: 503 service_unavailable won't clear on retry.
    if (res.status === 503 && body?.code === "service_unavailable") return res;
    // 502 service_unavailable is an ATS failure: retry it once.
    if (res.status === 502 && body?.code === "service_unavailable") {
      if (atsRetried) return res;
      atsRetried = true;
    }
    lastRes = res;
    if (attempt === maxRetries) break;

    // Prefer the server's Retry-After (seconds) when present.
    const retryAfter = res.headers.get("Retry-After");
    const waitMs =
      retryAfter && Number.isFinite(Number(retryAfter))
        ? Number(retryAfter) * 1000
        : backoff(attempt, baseDelayMs, maxDelayMs);

    await sleep(Math.min(waitMs, maxDelayMs));
  }

  return lastRes!; // exhausted retries — let the caller inspect the final status
}

/** Exponential backoff with full jitter. */
function backoff(attempt: number, base: number, max: number): number {
  const exp = Math.min(max, base * 2 ** attempt);
  return Math.random() * exp;
}
```

```typescript Usage theme={null}
import { randomUUID } from "node:crypto";

const res = await classetFetch("https://api.classet.ai/v2/candidates", {
  method: "POST",
  headers: { "Idempotency-Key": randomUUID() }, // retries can't double-send
  body: JSON.stringify({
    job_id: "k7Hq2xVbN",
    first_name: "Jordan",
    last_name: "Rivera",
    email: "jordan@example.com",
    send_sms: true,
  }),
});

if (res.ok) {
  const { data } = await res.json();
  console.log("created candidate", data.candidate_id);
} else if (res.status === 429) {
  // Cap exhausted even after retries — surface to the operator.
  const body = await res.json();
  console.warn(body.message ?? body.error, "retry at", body.retry_at);
} else {
  const body = await res.json();
  // Standard envelope on every error: { error, code, request_id }
  console.error(`[${body.code}] ${body.error} (request_id: ${body.request_id})`);
}
```

> [!NOTE]
>
> **Idempotency.** With an `Idempotency-Key`, retried `POST`s are exactly-once from your perspective: a successful outcome replays, a `5xx` outcome re-executes. Without a key, treat send endpoints as at-least-once and reconcile by candidate `id`/`external_id`. Full semantics in the [Idempotency guide](/docs/guides/idempotency.md).

## Quick rules

* Branch on `body.code` (stable) rather than the `body.error` text (may change).
* Retry **only** `429`, `503 rate_limit_unavailable`, `500`, `504`, and a `502` that isn't `service_unavailable`. Retry `502 service_unavailable` once. Never retry `503 service_unavailable`. Honor `Retry-After`; add jitter.
* Retry a `409` only when its `error` says the idempotency key is `already in progress` (a stopgap text match until it gets its own `code`).
* Send an `Idempotency-Key` on every `POST` you might retry.
* Watch `X-RateLimit-Remaining` to slow down before you hit `429`.
* Capture `request_id` / the `X-Request-Id` header and send it to support for any `5xx`.


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