Error Handling

All Toolkit API endpoints return errors in one consistent JSON envelope with a stable error_code string you can branch on. Don't parse detail — it's meant for humans and its wording can change. Branch on error_code and the HTTP status.

The error envelope

Every error response — whether it comes from the auth middleware, a route handler's HTTPException, or FastAPI's request validation — is shaped like this:

{
  "error_code": "INVALID_REQUEST",
  "error": "Invalid domain format: must be a valid FQDN",
  "detail": "Invalid domain format: must be a valid FQDN"
}
Field Type Always present Meaning
error_code string ✅ Stable machine-readable code (see catalogue below)
error string | object ✅ Short human message, or the validation detail list
detail string | object usually Raw detail from the handler; may be an object or array

error and detail usually carry the same string. Treat error as the display string and error_code as the contract.

Validation errors (HTTP 422)

When a request body or query string fails schema validation, the status is 422 and detail holds FastAPI's structured error list (an array of objects with loc, msg, type):

{
  "error_code": "REQUEST_VALIDATION_ERROR",
  "error": "Request validation failed",
  "detail": [
    {
      "loc": ["body", "points"],
      "msg": "List should have at least 2 items after validation, not 1",
      "type": "too_short"
    }
  ]
}

Each loc entry is a path into the request — ["body", "points"] means the points key of the JSON body. ["query", "radius"] means the radius query parameter.

How error_code is chosen

The resolver works in three passes:

  1. Known auth messages map to fixed codes — e.g. "Invalid or revoked API key" → INVALID_API_KEY, "Missing or invalid API key" → UNAUTHORIZED.
  2. Service-specific substrings — each toolkit registers its own patterns. For example the DNS service maps any detail containing "invalid domain:" to INVALID_DOMAIN_FORMAT.
  3. Fallback by status — if nothing matched, the code is derived from the HTTP status using the table below (or HTTP_<status>_ERROR for unusual codes).

This means a 400 from any endpoint always carries error_code: "INVALID_REQUEST" unless the toolkit has a more specific pattern for it.

Status → default error_code

HTTP error_code When it happens Retry?
400 INVALID_REQUEST Handler rejected the input (bad domain, unknown timezone, …) ❌ No
401 UNAUTHORIZED No API key supplied, or key rejected ❌ No
401 INVALID_API_KEY Key exists but is revoked / disabled ❌ No
403 FORBIDDEN Key valid but not entitled; or unverified email ❌ No
404 NOT_FOUND Unknown path, or resource (e.g. no timezone for coords) ❌ No
413 PAYLOAD_TOO_LARGE Uploaded file / body exceeds the limit ❌ No
422 REQUEST_VALIDATION_ERROR Body/query failed schema validation ❌ No
429 RATE_LIMITED Per-plan request rate exceeded ✅ After backoff
500 INTERNAL_SERVER_ERROR Unhandled server bug ✅ With backoff
502 UPSTREAM_ERROR An upstream provider errored ✅ With backoff
503 SERVICE_UNAVAILABLE Dependency missing/unavailable ✅ With backoff
504 UPSTREAM_TIMEOUT Upstream didn't answer in time ✅ With backoff

Two auth-specific codes can also appear when you route through RapidAPI:

error_code Meaning
INVALID_RAPIDAPI_PROXY_SECRET The X-RapidAPI-Proxy-Secret header didn't match

Handling errors in code

Python

Branch on error_code, not on the message text. Retry only the transient set.

import time
import httpx

RETRYABLE = {"RATE_LIMITED", "INTERNAL_SERVER_ERROR", "UPSTREAM_ERROR",
             "SERVICE_UNAVAILABLE", "UPSTREAM_TIMEOUT"}


def call(url: str, *, api_key: str, params: dict | None = None,
         json: dict | None = None, max_retries: int = 4) -> dict:
    for attempt in range(max_retries):
        r = httpx.request(
            "GET" if json is None else "POST",
            url, headers={"X-API-Key": api_key},
            params=params, json=json, timeout=30,
        )
        if r.status_code < 400:
            return r.json()

        body = r.json()
        code = body.get("error_code", f"HTTP_{r.status_code}")

        if code == "REQUEST_VALIDATION_ERROR":
            # detail is a list of {loc, msg, type}
            problems = "; ".join(
                f"{'.'.join(map(str, e['loc']))}: {e['msg']}"
                for e in body.get("detail", [])
            )
            raise ValueError(f"Invalid request — {problems}")

        if code == "INVALID_API_KEY" or code == "UNAUTHORIZED":
            raise PermissionError(body.get("error", "Check your API key"))

        if code in RETRYABLE and attempt < max_retries - 1:
            time.sleep(min(2 ** attempt, 30))
            continue

        raise RuntimeError(f"{code}: {body.get('error')}")

    raise RuntimeError("retries exhausted")

JavaScript

const RETRYABLE = new Set([
  "RATE_LIMITED", "INTERNAL_SERVER_ERROR", "UPSTREAM_ERROR",
  "SERVICE_UNAVAILABLE", "UPSTREAM_TIMEOUT",
]);

export async function call(url, { apiKey, method = "GET", body, retries = 4 } = {}) {
  for (let attempt = 0; attempt < retries; attempt++) {
    const resp = await fetch(url, {
      method,
      headers: { "X-API-Key": apiKey, "Content-Type": "application/json" },
      body: body ? JSON.stringify(body) : undefined,
    });

    if (resp.ok) return resp.json();

    const err = await resp.json().catch(() => ({}));
    const code = err.error_code ?? `HTTP_${resp.status}`;

    if (code === "REQUEST_VALIDATION_ERROR") {
      const problems = (err.detail ?? [])
        .map((e) => `${e.loc.join(".")}: ${e.msg}`)
        .join("; ");
      throw new Error(`Invalid request — ${problems}`);
    }
    if (code === "INVALID_API_KEY" || code === "UNAUTHORIZED") {
      throw new Error(`Auth failed: ${err.error ?? "check your API key"}`);
    }
    if (RETRYABLE.has(code) && attempt < retries - 1) {
      await new Promise((res) => setTimeout(res, Math.min(2 ** attempt, 30) * 1000));
      continue;
    }
    throw new Error(`${code}: ${err.error ?? "request failed"}`);
  }
  throw new Error("retries exhausted");
}

Retry strategy

Only retry the transient set: RATE_LIMITED, INTERNAL_SERVER_ERROR, UPSTREAM_ERROR, SERVICE_UNAVAILABLE, UPSTREAM_TIMEOUT.

  1. Wait ~1 s, retry
  2. Wait ~2 s, retry
  3. Wait ~4 s, retry
  4. Give up and surface the error

Always cap total retries and add jitter so a fleet of clients doesn't retry in lockstep. For 429 specifically, the limiter is a sliding second window — a one-second sleep is often enough to clear it; see Rate Limits.

Warning

Never retry 400, 401, 403, 404, 413 or 422. Those mean the request or credentials are wrong — retrying the identical request will fail the same way and burn quota.

Debugging checklist

  • UNAUTHORIZED on every call — X-API-Key missing or blank. If you use RapidAPI, send X-RapidAPI-Proxy-Secret instead (a wrong proxy secret returns 403 from the middleware or 401 from route-level checks).
  • REQUEST_VALIDATION_ERROR — read detail[].loc; it names the exact body key or query param that failed.
  • INVALID_REQUEST with a clear message — the schema was fine but the value was wrong (e.g. a nonexistent IANA timezone). The message is safe to show users.
  • NOT_FOUND on a valid path — for coordinate-driven endpoints this often means "no result" (e.g. a point in international waters has no timezone), not a missing endpoint.