# 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); Your role cannot change domains: buying, renewing, transfers and settings need an owner, admin or billing member; DNS, nameservers and forwarding need an owner, admin or developer. A `view` key, a trial key or an OAuth token can read domains and prices only | 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 |
| `connection_required` | 403 | This API reads one of your own accounts (GitHub, Google, Instagram…), and the workspace has not connected it. | No connected account for the provider named in `details.provider`; The key is not allowed to use connected accounts | Connect the account through `details.connectUrl` (or Connections in the dashboard), then retry. Nothing was charged. | After you act |
| `connection_needs_reauth` | 403 | The connected account stopped working: its access expired or was revoked on the provider’s side. | The access was revoked or expired at the provider (removed app access, password change, token lifetime) | Reconnect it through `details.connectUrl`, then retry. Nothing was charged. | After you act |
| `connection_access_off` | 403 | MCP only: the agent access rule for this API on this connected account is Off, so agents can’t run it. | Someone who manages the connection set the API (`details.source: "api"`) or a capability it needs (`details.source: "capability"`, named in `details.capability`) to Off | Ask a person who manages the connection to change the rule at `details.settingsUrl` (or `PUT /v1/connections/{id}/access`). Calls through the REST API with an API key are never refused this way. Nothing was charged. | After you act |
| `approval_required` | 403 | MCP only: the agent access rule for this API is Ask, so a person must approve this call before it runs. | APIs that change something at the provider ask by default; Someone set the API, or a capability it needs, to Ask | Give `details.approvalUrl` to a person who manages the connection. Once they approve, run the same call again with `approval: details.approvalId`; a different input needs a new approval. Nothing was charged. | After you act |
| `domains_not_allowed` | 403 | The workspace cannot register or transfer in domains yet. | `email_verified` in `details.missing`: the email address is not verified (the person signed in, or the workspace owner for an API key); `bought_credits` in `details.missing`: the workspace has never bought credits or paid for a plan. Welcome and trial credits do not count | Do what `details.missing` lists: verify the email (Settings › Profile sends a new link), buy credits once in Settings › Billing. Then send the same request again. Nothing was charged. | After you act |
| `domain_suspended` | 403 | PrimaryAPI suspended this domain: it can be read, not changed. | An abuse report or a charge-back on the workspace (`details.reason` says why) | Reads keep working. Contact support to discuss the suspension; nothing about the domain can change until it is lifted. | 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 |
| `domain_unavailable` | 409 | The domain cannot be registered or transferred in. | Someone else holds the name, or it was registered between your check and your order; The registry reserves the name, or its ending (TLD) is not offered; A transfer in for a name that is not registered, or that cannot move yet | Check another name with `POST /v1/domains/check` (`details.reason` says why this one failed). Nothing was charged. | No — change the request |
| `domain_price_limit` | 409 | The domain order would cost more than allowed. | A premium name ordered without `maxUsd`; The price is above the `maxUsd` you sent; The registrar’s price changed since your quote (`details.priceUsd`, `details.maxUsd`, `details.premium`) | Quote again with `POST /v1/domains/quote`; if the new price is fine, send the order with `maxUsd` at least that price. Nothing was charged. | After you act |
| `domain_conflict` | 409 | The domain’s current state blocks this change. | Changing DNS records or forwarding of a domain on custom nameservers: switch it back to the registrar’s DNS first (`PUT /v1/domains/{domain}/nameservers` with `{"useRegistrarDns": true}`); Another order on the domain is still in progress; The registration or transfer in is still pending; Deleting the default contact while the workspace has others | Read `details.reason`, do what it names, then send the request again. Nothing was charged. | After you act |
| `workspace_has_domains` | 409 | A workspace cannot be deleted while it holds live domains. | The workspace still holds domains that are registered to it | Transfer them to another registrar, or let them lapse, then delete the workspace. | After you act |
| `custom_id_taken` | 409 | Another monitor or connected account in this workspace already uses this `customId`. | A monitor that is not deleted already has the `customId` you sent (`details.monitorId` names it); A connected account that is not revoked already has it (`details.connectionId` names it); Two requests used the same `customId` at the same moment | Use another `customId`, or change the one that has it (`PATCH /v1/monitors/{id}` or `PATCH /v1/connections/{id}`). Deleting a monitor or revoking a connection 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 |
| `approval_unavailable` | 409 | The approval passed with the call can’t be used. | A person declined it; It was already used (each approval runs one call) or decided already; It expired (approvals last 24 hours); It is for another API, another input or another agent | Run the call again without `approval` to get a new approval link (`approval_required`). If it was declined, ask the person before trying again. | After you act |
| `invite_unavailable` | 410 | This connection invite link can no longer be used. | The account was already connected with it (invite links work once); It expired (links last 7 days unless set otherwise, at most 30); The workspace revoked it | Ask the workspace for a new link (`POST /v1/connections/{provider}/invites`). | After you act |
| `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 refused MCP requests in a minute from one network (no credentials, an unknown key, an expired sign-in or a disabled key); Too many agent trial keys created from one network in 24 hours, or the daily trial signup budget is spent; More than 10 new domains (registrations and transfers in) in one workspace in a UTC day | 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.
