# Errors

One flat error shape for every endpoint, every error code with its HTTP status, causes and fix, and what to retry. Errors are never charged.

Every error from every endpoint has the same flat JSON body, so one `switch` on `code` handles all of them:

```json title="402 Payment Required"
{
  "code": "insufficient_balance",
  "error": "not enough credits — buy credits to continue",
  "requestId": "req_01JBXV8M0P2R4T6V8X0Z2B4D6F"
}
```

| Field | Present | Meaning |
|---|---|---|
| `code` | always | Stable, machine-readable error code from the table below. |
| `error` | always | A human-readable explanation. Show it or log it; never parse it, since wording can change. |
| `requestId` | almost always | The id of this request. Include it when you contact support. Also sent as the `X-Request-Id` header. |
| `retryAfterSeconds` | sometimes | How long to wait before retrying. Also sent as the `Retry-After` header. |
| `details` | sometimes | Structured context, depending on the code (below). |
| `upgrade` | sometimes | On `trial_cap_reached`: `{ claimUrl, authorizationServer, scope }`. |

Three rules cover most of error handling:

1. **Errors are never charged.** A 4xx means nothing ran or nothing was billed; a 5xx means every attempt failed and the credits held for the call came back.
2. **Branch on `code`**, not on the HTTP status alone (three codes share 401, three share 402) and never on the message.
3. **"Not found" data is not an error.** A profile that does not exist comes back as a `200` with `output.found: false`. The `not_found` error is about URLs: an unknown SKU or request id.

## Error codes

| Code | HTTP | Meaning | Common causes | What to do | Retry? |
|---|---|---|---|---|---|
| `invalid_input` | 400 | The request failed validation before anything ran. | An input field the API does not declare (inputs are strict: unknown keys are rejected, never ignored); A required field is missing, or a value is the wrong type or outside its allowed range; A routing control is wrong: `preferLatencyUnderMs` or `maxCredits` is not a positive whole number, `maxCredits` is below what this input can be served for (`details.cheapestCredits`), or the request still sends `maxCostUsd`, which `maxCredits` replaced; A malformed `Idempotency-Key` header (it must be 1–255 visible ASCII characters); The input itself was rejected as invalid upstream (retrying it unchanged would fail the same way) | Read `details` (for schema errors it lists each issue with its path), compare with the API’s `inputSchema` from `GET /v1/apis/{sku}`, correct the request and send it again. | No — change the request |
| `unauthorized` | 401 | No valid API key or session was presented. | The `Authorization: Bearer …` or `X-API-Key` header is missing; The key is truncated, mistyped, unknown or revoked (all four give the same answer on purpose) | Send the whole key, which starts with `pa_live_`. If it was revoked or lost, create a new key in the dashboard. | No — change the request |
| `key_disabled` | 401 | The key exists but has been disabled. | Someone on the account disabled it in the dashboard or with `PATCH /v1/api-keys/{id}` | Re-enable it with `{"disabled": false}` (a full-access key or the dashboard), or switch to another key. | After you act |
| `key_expired` | 401 | The key has passed its expiry time. | The key was created with an expiry (`expiresIn`) that has now passed; An agent trial key reached the end of its trial period without being claimed | Expiry cannot be extended. Create a new key. For a trial key, ask a human to open the claim link from the signup response. | After you act |
| `insufficient_balance` | 402 | The balance cannot cover the most this call could cost. | The workspace has fewer credits (bought, welcome and included with a plan) than the most the call can cost (its quote’s `maxCredits`); The account’s keys are paused: the balance stayed empty for more than 48 hours while calls kept being refused | Buy credits in the dashboard (Settings › Billing), or lower `limit` so the call can cost less. Paused keys resume on their own once the balance can pay; nothing else needs to change. | After you act |
| `payment_failed` | 402 | A plan payment was declined, so the plan did not change. | The card on file was declined for an upgrade, which charges for the rest of the billing period | Update the card under Billing details in Settings › Billing › Plans, then make the change again. Nothing was charged. | After you act |
| `trial_cap_reached` | 402 | An agent trial key has used its whole trial budget. | The trial key minted by `POST /agent/signup` spent its `capCredits` | Relay `upgrade.claimUrl` from the error body to a human. Once they approve, the same key keeps working on their workspace’s credits, within the spend limit they set. | After you act |
| `key_limit_reached` | 402 | The key’s own spend limit is used up for the current window. | The key has `limitCredits` per `daily`, `weekly` or `monthly` window (UTC; weeks start Monday), or a lifetime limit | Wait for `windowResetsAt`, raise the limit with `PATCH /v1/api-keys/{id}`, or use a different key. The workspace’s credits are untouched. | After you act |
| `forbidden` | 403 | The credential is valid but may not do this. | The key’s access level is too low: a `view` key cannot run or quote APIs; a `run` key cannot read the balance, usage or keys; A browser-session request came from an origin we do not accept (cross-site request protection) | Use a key with the access level the endpoint lists, or create one in the dashboard. | No — change the request |
| `insufficient_scope` | 403 | An OAuth access token is valid but was not granted the permission this endpoint needs. | The app was approved without the scope, for example `wallet:read` but not `apis:run`; The person who approved it no longer has a role in the workspace that allows it | Ask for authorization again with the scope from the `WWW-Authenticate` header (`details.requiredScopes` lists every scope that works). | After you act |
| `restricted_api` | 403 | This API handles sensitive personal data and your account is not approved for it. | The API is marked restricted and the account has not accepted the permissible-purpose terms or been approved | Request access and describe your permissible purpose (see Restricted APIs). Other APIs keep working meanwhile. | After you act |
| `not_found` | 404 | The thing addressed by the URL does not exist for you. | An unknown SKU, or one that is planned or deprecated; A request, result or key id that does not exist or belongs to another account; A stored result that is not ready yet, has passed its retention window, or belongs to a failed request (`GET /v1/results/{id}`); An agent claim link that is invalid or has expired | Check the SKU with `GET /v1/apis`. This code is never used for “the profile you looked up does not exist”: that is a successful call with `output.found: false`. | No — change the request |
| `idempotency_conflict` | 409 | The `Idempotency-Key` is already bound to a different request. | The same key was sent with a different SKU, input or routing controls within the retention window; Two requests with the same new key started at the same moment (the body carries `retryAfterSeconds`); A change was attempted on an API key that has been revoked | Use a fresh `Idempotency-Key` for every new call. Reuse a key only to retry exactly the same request. | No — change the request |
| `custom_id_taken` | 409 | Another monitor in this workspace already uses this `customId`. | A monitor that is not deleted already has the `customId` you sent (`details.monitorId` names it); Two requests used the same `customId` at the same moment | Use another `customId`, or change the monitor that has it (`PATCH /v1/monitors/{id}`). Deleting a monitor frees its `customId`. | After you act |
| `workspace_has_balance` | 409 | A workspace cannot be deleted while it still holds credits. | Credits are left in the workspace (`details.balanceCredits`) | Credits are non-refundable: use them, then delete the workspace. | After you act |
| `workspace_has_plan` | 409 | A workspace cannot be deleted while it is on a paid plan. | The workspace’s plan is still running, including a plan cancelled for the end of its period or one with an unpaid invoice | Cancel the plan in Settings › Billing › Plans, then delete the workspace once the plan has ended. | After you act |
| `workspace_busy` | 409 | A workspace cannot be deleted while money is still moving in it. | Calls are still running in the workspace; A card purchase of credits for the workspace may still be paid (up to 24 hours) | Wait until running calls finish or the pending purchase expires, then try again. | After you act |
| `last_workspace` | 409 | You cannot delete your only workspace. | The caller belongs to no other workspace | Create or join another workspace first, then delete this one. | After you act |
| `last_owner` | 409 | A workspace always has exactly one owner, who cannot be demoted or removed. | The request changes the role of, or removes, the workspace owner | Change other members instead. To shut the workspace down, the owner deletes it. | No — change the request |
| `unprocessable` | 422 | The request is well formed but cannot be carried out as asked. | This API cannot serve this particular input (for example a country or format it does not cover); Creating an API key when the account already has 100 active keys | Change the input (or revoke keys you no longer use). Nothing was charged, and the same request gives the same answer, so do not loop on it. | No — change the request |
| `rate_limited` | 429 | Too many requests in the current window. | More than 200 requests in 10 seconds on one key, or more than 1,000 requests in a minute on one account; More than 120 keyless MCP requests in a minute from one IP address; Too many agent trial keys created from one network in 24 hours, or the daily trial signup budget is spent | Wait for the `Retry-After` header (also `retryAfterSeconds` in the body), then retry with backoff. | Yes, with backoff |
| `internal_error` | 500 | Something failed on our side. | An unexpected server error | Retry with backoff, reusing the same `Idempotency-Key` so a retry can never run twice. If it persists, report it with the `requestId`. | Yes, with backoff |
| `all_sources_failed` | 502 | The call could not be answered, even after automatic retries. | Every attempt timed out, errored, was rate limited or blocked upstream | Nothing was charged: the credits set aside for the call came back in full. Retry later with backoff, reusing the same `Idempotency-Key`; the Network page shows live status. | Yes, with backoff |
| `source_unavailable` | 502 | Retired: no longer returned. It belonged to the removed source-selection controls. | Not returned by the current API; old clients may still list it | Nothing to do. Treat it like `all_sources_failed` if an old integration still checks for it. | Yes, with backoff |
| `service_unavailable` | 503 | This API cannot run in this deployment right now. | The API is not connected in this deployment yet; The gateway is restarting (the body carries `retryAfterSeconds`) | Try again later and check the Network page for live status. | Yes, with backoff |
| `timeout` | 504 | The request passed its deadline before it finished. | The request ran out of time before it was answered; A durable request passed its deadline (15 minutes by default) and was expired | Nothing was charged. For slow APIs send `Prefer: respond-async` and poll `GET /v1/requests/{id}`; retry with the same `Idempotency-Key`. | Yes, with backoff |

## What details contain

| Code | `details` |
|---|---|
| `invalid_input` (schema) | The list of validation issues, each with `path`, `message` and `code`. |
| `invalid_input` (`maxCredits` too low) | `{ "maxCredits": 10, "cheapestCredits": 17 }`: your cap, and the least this input can be served for. |
| `invalid_input` (retired `maxCostUsd` sent) | `{ "field": "maxCostUsd", "replacement": "maxCredits" }` |
| `key_limit_reached` | `limitCredits` (the key's limit), `spentCredits` (spent in the current window), `requiredCredits` (what the call needs), `limitInterval` and `windowResetsAt`. |
| `workspace_has_balance` | `{ "balanceCredits" }`: the credits left in the workspace. Credits are non-refundable, so use them before deleting the workspace. |
| `idempotency_conflict` | `{ "requestId" }` of the request that owns the key. |
| any replayed failure | `{ "replayed": true, "requestId" }` when an `Idempotency-Key` returned an earlier deterministic error. |

`all_sources_failed`, `timeout`, `unprocessable` and an `invalid_input` raised because the upstream rejected the input carry no `details`: which upstream was tried is internal. Quote the `requestId` and support can see every attempt.

`source_unavailable` is a legacy code: it was returned when the retired `source` / `allowFallbacks` controls excluded every route, and is no longer produced. Keep handling it as "not charged, do not retry unchanged" if your client already does.

## Retry or not

| Retry | Codes |
|---|---|
| With backoff, unchanged | `rate_limited`, `internal_error`, `all_sources_failed`, `service_unavailable`, `timeout` |
| After you fix something | `insufficient_balance`, `key_limit_reached`, `trial_cap_reached`, `key_disabled`, `key_expired`, `restricted_api` |
| Never unchanged | `invalid_input`, `unauthorized`, `forbidden`, `not_found`, `idempotency_conflict`, `unprocessable` |

Retry with the same `Idempotency-Key` so a retry can never run twice, and honour `Retry-After` when it is present. [Idempotency and retries](/docs/idempotency) has complete retry helpers in TypeScript and Python.

## Handling errors in code

```ts
type ApiError = {
  code: string;
  error: string;
  requestId?: string;
  retryAfterSeconds?: number;
  details?: unknown;
  upgrade?: { claimUrl?: string };
};

class RetryableError extends Error {
  constructor(
    readonly body: ApiError,
    readonly retryAfterSeconds?: number,
  ) {
    super(`${body.code}: ${body.error}`);
  }
}

async function call(sku: string, input: object) {
  const res = await fetch(`https://api.primaryapi.com/v1/run/${sku}`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.PRIMARYAPI_API_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify(input),
  });
  if (res.ok) return res.json(); // 200 envelope, or 202 snapshot while it runs

  const err = (await res.json()) as ApiError;
  switch (err.code) {
    case 'invalid_input':
      throw new Error(`Fix the input: ${err.error}`); // see err.details for every issue
    case 'insufficient_balance':
    case 'key_limit_reached':
      throw new Error(`Out of credits: ${err.error}`); // buy credits or raise the key's limit
    case 'trial_cap_reached':
      throw new Error(`Ask a human to approve this key: ${err.upgrade?.claimUrl}`);
    case 'rate_limited':
    case 'all_sources_failed':
    case 'service_unavailable':
    case 'timeout':
    case 'internal_error':
      throw new RetryableError(err, err.retryAfterSeconds); // retry with the same Idempotency-Key
    default:
      throw new Error(`${err.code}: ${err.error} (request ${err.requestId})`);
  }
}
```

## Reporting a problem

If an error looks like our fault, or data looks wrong, tell us with the `requestId`:

- `POST /v1/bug-reports` with `{"message": "…", "requestId": "req_…", "sku": "…"}` (any key; see [Feedback](/docs/api-reference/feedback)),
- the `report_bug` tool in the [MCP server](/docs/mcp-server),
- or email support@primaryapi.com.

Never put an API key in a report.
