# 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.

Canonical: https://currency-core.com/docs/code-examples/
Updated: 2026-11-10
Published: 2026-06-04

---
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](https://app.currency-core.com). See [Authentication](/docs/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.

<CodeTabs>
<Fragment slot="js">

```js
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 })
```

</Fragment>
<Fragment slot="python">

```python

BASE = "https://api.currency-core.com/v1"
KEY = os.environ["CURRENCYCORE_API_KEY"]

class ApiError(Exception):
    def __init__(self, status, body, headers):
        super().__init__(body.get("error", {}).get("message", f"HTTP {status}"))
        self.status = status
        self.body = body
        self.headers = headers

def call(path, **params):
    res = requests.get(
        BASE + path,
        params={k: v for k, v in params.items() if v not in (None, "")},
        headers={"Authorization": f"Bearer {KEY}"},
        timeout=10,
    )
    body = res.json()
    if not res.ok:
        raise ApiError(res.status_code, body, res.headers)
    return body

# Example: call("/rates/EUR", date="2024-11-01")
```

</Fragment>
</CodeTabs>

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

```json
{
  "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](/docs/sdks/). Do not add a dependency just to set two headers.

## Read the error before retrying

| Status | Code | Retry? | Action |
|---|---|---|---|
| `400` | `invalid_input` or `unknown_currency` | No | Fix the query. The same request will fail again. |
| `401` | `unauthorized` | No | Check the key and header. |
| `402` | `forbidden` | No | Billing is past due. Clear payment. |
| `403` | `forbidden` | No | Plan gate, disabled key, or Free history window. |
| `404` | `rate_not_found` or `unknown_ppp` | No | Choose a date or country that has data. |
| `429` | `rate_limited` | Yes | Wait for `Retry-After`, then retry. |
| `500` | `internal_error` | Yes | Retry 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.

<CodeTabs>
<Fragment slot="js">

```js
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"));
```

</Fragment>
<Fragment slot="python">

```python

def with_retry(fn, attempts=3):
    for i in range(attempts):
        try:
            return fn()
        except ApiError as err:
            retryable = err.status == 429 or err.status >= 500
            if not retryable or i == attempts - 1:
                raise
            retry_after = err.headers.get("Retry-After")
            base = float(retry_after) if retry_after not in (None, "") else 0.5 * (2 ** i)
            time.sleep(base + random.random() * 0.25)

data = with_retry(lambda: call("/rates/EUR"))
```

</Fragment>
</CodeTabs>

## Practical rules

- **Cache reference data.** [`/v1/countries`](/docs/countries/) and [`/v1/currencies`](/docs/currencies/) are public and unmetered. Fetch them once and refresh on a schedule.
- **Batch targets, not requests.** [`/v1/convert`](/docs/convert-endpoint/) 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](/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](/docs/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`](/docs/currencies/) needs no key, so it checks connectivity and JSON parsing. [`/v1/rates`](/docs/rates-endpoint/) 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

- [Getting started](/docs/getting-started/) for the full endpoint table
- [Errors](/docs/errors/) for the complete error-code reference
- [Convert endpoint](/docs/convert-endpoint/) for the most common call
- [SDKs](/docs/sdks/) for typed clients
- [MCP server](/mcp-server/) for agent integrations
