Code Examples

Client Setup, Errors, and Retries

Set up a reusable CurrencyCore client, read the error envelope, and retry 429 and 5xx responses safely with backoff and Retry-After.


Every data endpoint is a plain GET, and the metered endpoints share the same authenticated plumbing. This page covers that plumbing once, so the endpoint pages can stay focused on parameters and response fields.

Replace cc_live_your_key with a key from your dashboard. See Authentication for key types and headers.

Base client

Use the same key header and base URL for every call. The API accepts either Authorization: Bearer <key> or x-api-key: <key>. Keep the key on the server, never in browser code or a public repository.

const BASE = "https://api.currency-core.com/v1";
const KEY = process.env.CURRENCYCORE_API_KEY;

class ApiError extends Error {
  constructor(status, body, headers) {
    super(body?.error?.message ?? `HTTP ${status}`);
    this.status = status;
    this.body = body;
    this.headers = headers;
  }
}

async function call(path, params = {}) {
  const url = new URL(BASE + path);
  for (const [k, v] of Object.entries(params)) {
    if (v !== undefined && v !== null && v !== "") url.searchParams.set(k, v);
  }
  const res = await fetch(url, {
    headers: { Authorization: `Bearer ${KEY}` },
    signal: AbortSignal.timeout(10_000),
  });
  const body = await res.json();
  if (!res.ok) throw new ApiError(res.status, body, res.headers);
  return body;
}

// Example: call("/convert", { from: "USD", to: "INR", amount: 100 })

The response shape is always the documented JSON body. Failures always use the error envelope:

{
  "error": {
    "code": "invalid_input",
    "message": "Both `from` and `to` currency codes are required."
  }
}

No SDK required

You do not need a client library to follow this page. The examples use the standard fetch API in JavaScript and the requests library in Python, both of which are enough for production calls. If you prefer typed models and generated methods, use an official SDK. Do not add a dependency just to set two headers.

Read the error before retrying

StatusCodeRetry?Action
400invalid_input or unknown_currencyNoFix the query. The same request will fail again.
401unauthorizedNoCheck the key and header.
402forbiddenNoBilling is past due. Clear payment.
403forbiddenNoPlan gate, disabled key, or Free history window.
404rate_not_found or unknown_pppNoChoose a date or country that has data.
429rate_limitedYesWait for Retry-After, then retry.
500internal_errorYesRetry with exponential backoff.

Do not retry a 4xx other than 429. Retrying a validation error wastes your rate budget without changing the result.

Retry 429 and 5xx safely

Use the Retry-After header when present. It is a number of seconds. Add jitter and cap the number of attempts.

async function withRetry(fn, attempts = 3) {
  for (let i = 0; i < attempts; i++) {
    try {
      return await fn();
    } catch (err) {
      const status = err.status;
      const retryable = status === 429 || status >= 500;
      if (!retryable || i === attempts - 1) throw err;

      const retryAfter = Number(err.headers.get("Retry-After"));
      const baseMs = Number.isFinite(retryAfter) && retryAfter > 0
        ? retryAfter * 1000
        : 500 * 2 ** i;
      const jitter = Math.random() * 250;
      await new Promise((r) => setTimeout(r, baseMs + jitter));
    }
  }
}

const data = await withRetry(() => call("/rates/EUR"));

Practical rules

  • Cache reference data. /v1/countries and /v1/currencies are public and unmetered. Fetch them once and refresh on a schedule.
  • Batch targets, not requests. /v1/convert accepts a comma-separated to list, so one call can convert to many currencies.
  • Respect plan windows. Free history is limited to 30 days, and the analytics endpoints require Growth. See Pricing.
  • Watch the rate budget. Errored calls still consume the per-minute rate limit, even when they are not counted toward the monthly quota. See Authentication for limits.
  • Keep requests small. Use the endpoint-specific limit caps instead of fetching everything and filtering locally.
  • Use UTC dates. Send YYYY-MM-DD dates and store the returned dates as UTC. The API does not convert to your local timezone.

Verify the setup

Before building features, make one call you can reason about. /v1/currencies needs no key, so it checks connectivity and JSON parsing. /v1/rates checks the key and returns a familiar payload. If the first call succeeds and the second returns 401, the problem is the header, not the network.

Timeouts

Set a client timeout and cancel abandoned requests. A slow upstream should not hold a worker or a request thread open. In Node, pass signal: AbortSignal.timeout(10_000) to fetch. In Python, pass timeout=10 to requests.get.

A timeout is retryable only when the request is safe to repeat. Every documented endpoint here is a GET, so repeating one does not change server state, but still cap attempts and use backoff.

Next steps