# Errors

When a call fails, the API answers with an HTTP status of 400 or above and the same JSON envelope every time:

```json
{
  "error": {
    "type": "insufficient_credits",
    "message": "Credit balance is 0.",
    "docs": "https://qelka.com/docs/errors#insufficient_credits"
  }
}
```

| Field | Type | Description |
|---|---|---|
| `error.type` | string | One of the nine types below. Stable: write your code against it. |
| `error.message` | string | A sentence for humans that explains this particular failure. It can change at any time: show it or log it, never parse it. |
| `error.docs` | string | Link to the section of this page for the type. |

The response also carries an `X-Request-Id` header. Log it with the error: it lets support find the request without you sending us the data you were checking.

## The nine types at a glance

| HTTP status | Type | Billed | Retry? |
|---|---|---|---|
| 400 | [invalid_request](#invalid_request) | No | No, fix the request |
| 401 | [invalid_api_key](#invalid_api_key) | No | No, fix the key |
| 402 | [insufficient_credits](#insufficient_credits) | No | Only after adding credits |
| 403 | [forbidden](#forbidden) | No | No, use another key |
| 404 | [not_found](#not_found) | No | No, fix the path or id |
| 422 | [unprocessable_input](#unprocessable_input) | No | No, the value cannot be checked |
| 429 | [rate_limited](#rate_limited) | No | Yes, after `Retry-After` seconds |
| 500 | [internal_error](#internal_error) | No | Yes, with backoff |
| 502 | [upstream_unavailable](#upstream_unavailable) | No | Yes, with backoff |

No error is billed: a failed call never takes credits from your balance.

## Handling errors in code

Branch on `error.type`, retry only what can succeed on a second try, and keep the request id:

```javascript
const retryable = new Set(['rate_limited', 'internal_error', 'upstream_unavailable'])

export async function verifyEmail(email) {
  const response = await fetch('https://api.qelka.com/v1/email', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ email }),
  })
  const body = await response.json()
  if (response.ok) return body
  const { type, message } = body.error
  const failure = new Error(`${type}: ${message}`)
  failure.type = type
  failure.retryable = retryable.has(type)
  failure.retryAfter = Number(response.headers.get('Retry-After')) || null
  failure.requestId = response.headers.get('X-Request-Id')
  throw failure
}
```

The [JavaScript SDK](/docs/sdk-js) does this for you: it throws an `ApiError` with `type`, `status`, `message`, `requestId` and `retryAfter`, and retries `429`, `502` and `503` responses on its own. [Rate limits](/docs/rate-limits) has a complete retry loop with backoff.

## invalid_request

**HTTP status:** 400. **Billed:** no.

**When it happens.** The request does not match the endpoint's schema:

- the body is empty, is not valid JSON, or is larger than 1 MB on a JSON endpoint;
- a required field is missing: `phone`, `email`, `ip` or `items`;
- a field has the wrong type, such as a number for `phone` or a string for `fresh`;
- a value is outside the allowed set, such as a `level` other than `basic` or `live`, or a `mode` other than `full` or `fast`;
- a field is not part of the endpoint: requests are strict, so sending `level` to `/email` is an error rather than being ignored;
- a value is too long or too short: `phone` over 64 characters, `email` over 320, `country` that is not two letters;
- a batch has no items or more than 100;
- a bulk request is missing its `type` or `column` query parameter.

**What to do.** Read `error.message`, which names the field and the problem, fix the request and send it again. Sending the same request again will fail the same way.

Calling an endpoint with the wrong HTTP method, such as `GET /v1/phone`, returns the same type with the HTTP status `405` and an `Allow` header that lists the right method.

## invalid_api_key

**HTTP status:** 401. **Billed:** no.

**When it happens.** The API cannot authenticate the request:

- there is no `Authorization` header, or it does not use the `Bearer` scheme;
- the key is mistyped, truncated or does not exist;
- the key has been revoked. Revocation takes effect within 60 seconds.

**What to do.** Check that the header reads `Authorization: Bearer sk_live_...` or `Authorization: Bearer sk_test_...`. Compare the key's first characters with the prefixes listed in the dashboard. If the key was revoked or lost, create a new one. See [Authentication](/docs/authentication).

## insufficient_credits

**HTTP status:** 402. **Billed:** no.

**When it happens.** Your balance cannot cover the call: for example a live phone lookup, which costs 3 credits, with fewer than 3 credits left. A batch needs enough credits for its items, and a bulk job reserves credits for every row when it is created, so a large file can be refused while single calls still go through.

**What to do.** Add credits by upgrading your plan or buying a credit pack on the [pricing page](/pricing), or wait for your plan's next monthly credits. While you build, use a test key: it never debits credits. To see this coming, read `X-Credits-Remaining` on each response or subscribe to the `credits.low` [webhook](/docs/webhooks). See [Credits](/docs/credits).

## forbidden

**HTTP status:** 403. **Billed:** no.

**When it happens.** The key is valid but not allowed to do this:

- the key is restricted to other endpoints;
- a test key was used for something that needs a live key, such as creating a bulk job with `POST /bulk`;
- a bulk download link is invalid or has expired. Call `GET /bulk/{id}` for a fresh one.

**What to do.** Call with a key whose restrictions include this endpoint, or with a live key for bulk jobs. The dashboard shows the restrictions of each key.

## not_found

**HTTP status:** 404. **Billed:** no.

**When it happens.** The thing you asked for does not exist:

- `GET /bulk/{id}` with an id that does not match a bulk job of your organization;
- a path that is not part of the API, often a missing `/v1` prefix or a typo in the endpoint name.

**What to do.** Check the base URL (`https://api.qelka.com/v1`), the method and the path against the [API reference](/docs/api-reference). Bulk job ids start with `bulk_` and come from the `POST /bulk` response.

## unprocessable_input

**HTTP status:** 422. **Billed:** no.

**When it happens.** The request is well formed, but the value in it cannot be checked:

- an IP address that does not parse, such as `999.1.1.1`;
- a private, loopback, link-local, documentation or other special-purpose IP address listed in the IANA registries described by RFC 6890, such as `10.0.0.1`, `127.0.0.1` or `203.0.113.42` (test keys return sample data for the documentation ranges, see [Test mode](/docs/test-mode));
- other malformed input that cannot be read.

**What to do.** Do not retry: the answer will not change. If the value comes from your own traffic, a 422 usually means you are looking up an internal address. In local development, your server sees `127.0.0.1` or `::1`, so treat a 422 as "no signal" rather than as a failure. Behind a proxy or load balancer, make sure you read the client address from the right header. In a batch, the same failure comes back as an error item and the other items still run.

An email address with bad syntax is not an error: it returns `200` with `status: "undeliverable"` and `reason: "invalid_syntax"`.

## rate_limited

**HTTP status:** 429. **Billed:** no.

**When it happens.** You went over one of the two rate limits: 200 requests per 10 seconds for the key, or 1,000 requests per 60 seconds for your organization, all keys combined. The response carries a `Retry-After` header with the number of seconds to wait.

**What to do.** Wait `Retry-After` seconds, then send the request again. If you hit the limit often, slow down on your side: process work through a queue, use [`/batch`](/docs/api-reference/batch) for many values at once, or a [bulk job](/docs/api-reference/bulk) for files. See [Rate limits](/docs/rate-limits).

## internal_error

**HTTP status:** 500. **Billed:** no.

**When it happens.** Something failed on our side that is not your request's fault.

**What to do.** Retry a few times with exponential backoff, for example after 1, 2, then 4 seconds. If the error persists, check the [status page](/status) and write to support@qelka.com with the `X-Request-Id` of a failed call.

## upstream_unavailable

**HTTP status:** 502. **Billed:** no.

**When it happens.** A provider the call depends on did not answer. Today this happens on live phone lookups (`"level": "live"`) when the carrier lookup provider fails.

**What to do.** Retry later with backoff, or fall back to `"level": "basic"`, which reads the numbering plan and does not depend on the provider. Basic results carry the carrier the range was originally assigned to rather than the current one, and `ported` is null.

When the mailbox check of an email cannot run, the API does not return this error. It answers `200` with `status: "unknown"`, `reason: "smtp_unavailable"` and `credits_used: 0`, so you still get the syntax, DNS and list checks at no cost.

## Errors inside a batch

[`POST /batch`](/docs/api-reference/batch) returns `200` as long as the request itself is valid. An item that fails takes its place in `data` as an error object with its position in `items`:

```json
{
  "object": "list",
  "data": [
    {
      "object": "error",
      "index": 0,
      "error": { "type": "unprocessable_input", "message": "10.0.0.1 is in Private-Use (RFC 1918) and has no public location." }
    }
  ],
  "credits_used": 0
}
```

Item errors use the same types as above, are not billed, and have no `docs` field. Errors that concern the whole request, such as an invalid key or more than 100 items, still use the regular envelope and HTTP status.
