Handle errors

Last checked:

The error shape

Every error answer is JSON with at least a message. Most also carry the typed code to branch on in data.code:

{
  "name": "Forbidden",
  "message": "…",
  "code": 403,
  "className": "forbidden",
  "data": { "code": "API_TOKEN_SCOPE_DENIED" },
  "errors": {}
}
  • Branch on the HTTP status and data.code. Never parse message: its wording may change.
  • Show message to a person if you need to: it never contains internal details.
  • errors, when present, maps each field to what is wrong with it.

A few refusals come straight from a route and carry only message, for example a record that doesn’t exist (404). Handle a missing data as “no typed code”.

Status codes

Status data.code Meaning What to do
400 — The request is malformed, or an action refused its input. errors names each field. Fix the request. Don’t retry as is.
400 IDEMPOTENCY_KEY_INVALID The Idempotency-Key header isn’t 1–128 characters of A–Z a–z 0–9 . _ : -. Send a valid key.
401 API_TOKEN_OWNER_INACTIVE The token is unknown, revoked, expired, or its owner can no longer sign in. Get a new token from the business.
401 API_TOKEN_SCOPE_DENIED This route isn’t open to API tokens. Use only operations in the reference.
402 SUBSCRIPTION_READ_ONLY, SUBSCRIPTION_EXPIRED The business’s subscription allows no changes now, or has ended. Stop writing; tell the business.
402 PLAN_LIMIT_REACHED The plan’s limit for this kind of record is reached. data adds key, limit and used. Tell the business.
403 API_TOKEN_SCOPE_DENIED The token’s scopes don’t cover this operation. Ask for a token with the right scope.
403 ACCESS_DENIED The token’s owner isn’t allowed to do this now. Ask the business to check the owner’s role.
403 RATE_LIMITED Too many requests from your address: blocked for a while. Wait data.retry_after_seconds. See rate limits.
404 FEATURE_DISABLED The feature behind this operation is off for this business. Tell the business.
404 — No such record in this business. Don’t retry.
409 IDEMPOTENCY_IN_PROGRESS, IDEMPOTENCY_RESULT_UNAVAILABLE See idempotency.
422 IDEMPOTENCY_KEY_REUSED The same Idempotency-Key was sent with another body. Use a new key for a new request.
429 RATE_LIMITED Over a rate limit. Wait retry-after seconds, then retry.
500 — Something failed on the server. The message is always generic. A read, or an action sent with an Idempotency-Key: retry later with backoff. Any other action may have run: read the records first.

Field errors are 400, not 422. A 409 or 422 comes only from operations that take an Idempotency-Key.

Field errors

When an action refuses its input, errors names each field:

{
  "name": "BadRequest",
  "message": "Please fix the highlighted fields",
  "code": 400,
  "className": "bad-request",
  "data": {},
  "errors": { "customer_name": "Customer Name is required." }
}

Which fields an action requires can depend on the business’s own settings. Read errors to learn which ones are missing; don’t rely on a fixed list.

Retry only what can succeed later

A 429, or a 403 with data.code RATE_LIMITED, is refused before anything runs: wait as it says, then send the same request again.

After a 500, a timeout or a lost connection you can’t tell whether the request ran. Retry it automatically only when running it twice can do no harm:

  • a read (GET);
  • an action sent with an Idempotency-Key, retried with the same key and the same body (see idempotency).

Never retry automatically an action that takes no Idempotency-Key, or that you sent without one: it may already have run, and a retry would run it again. Read the records first to see whether it did, then decide.

The helpers below follow these rules, with a growing wait between tries.

Node.js

// Retries a 429 / RATE_LIMITED refusal; a 5xx or a network failure only for a GET or a request with an Idempotency-Key.
async function call(url, init = {}, tries = 4) {
  const method = (init.method ?? "GET").toUpperCase();
  const repeatable = method === "GET" || new Headers(init.headers).has("Idempotency-Key");
  for (let attempt = 1; ; attempt++) {
    let response;
    try {
      response = await fetch(url, init);
    } catch (error) {
      if (!repeatable || attempt >= tries) throw error;
      await new Promise((done) => setTimeout(done, 2 ** attempt * 1000));
      continue;
    }
    if (response.ok) return response.json();
    const answer = await response.json().catch(() => ({}));
    const limited = response.status === 429 || answer.data?.code === "RATE_LIMITED";
    if (attempt >= tries || !(limited || (repeatable && response.status >= 500))) {
      throw new Error(`${response.status} ${answer.data?.code ?? ""}: ${answer.message ?? ""}`);
    }
    const wait = Number(response.headers.get("retry-after")) || answer.data?.retry_after_seconds || 2 ** attempt;
    await new Promise((done) => setTimeout(done, wait * 1000));
  }
}

Python

import time
import requests

# Retries a 429 / RATE_LIMITED refusal; a 5xx or a network failure only for a GET or a request with an Idempotency-Key.
def call(method, url, tries=4, **kwargs):
    headers = {name.lower() for name in (kwargs.get("headers") or {})}
    repeatable = method.upper() == "GET" or "idempotency-key" in headers
    for attempt in range(1, tries + 1):
        try:
            response = requests.request(method, url, timeout=30, **kwargs)
        except requests.RequestException:
            if not repeatable or attempt == tries:
                raise
            time.sleep(2 ** attempt)
            continue
        if response.ok:
            return response.json()
        answer = response.json() if response.content else {}
        limited = response.status_code == 429 or (answer.get("data") or {}).get("code") == "RATE_LIMITED"
        if attempt == tries or not (limited or (repeatable and response.status_code >= 500)):
            raise RuntimeError(f"{response.status_code} {(answer.get('data') or {}).get('code', '')}: {answer.get('message', '')}")
        wait = int(response.headers.get("retry-after") or (answer.get("data") or {}).get("retry_after_seconds") or 2 ** attempt)
        time.sleep(wait)