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_keywith 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 })import os
import requests
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")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
| 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.
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"));import random
import time
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"))Practical rules
- Cache reference data.
/v1/countriesand/v1/currenciesare public and unmetered. Fetch them once and refresh on a schedule. - Batch targets, not requests.
/v1/convertaccepts a comma-separatedtolist, 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
limitcaps instead of fetching everything and filtering locally. - Use UTC dates. Send
YYYY-MM-DDdates 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
- Getting started for the full endpoint table
- Errors for the complete error-code reference
- Convert endpoint for the most common call
- SDKs for typed clients
- MCP server for agent integrations