Most currency API snippets are one line: get(url).json()["rate"]. Production code needs a few more things in every language:
- a timeout, so a slow network doesn't hang your request handler;
- a retry on transient errors (
5xx, timeouts), but not on4xx; - a cache, because rates update every 60 seconds and you don't need them more often;
- exact decimals for money.
Here's that, in Python, Go and PHP, against AllRatesToday's API. All three need a free API key in ALLRATES_KEY.
The call is the same everywhere:
GET https://allratestoday.com/api/v1/rates?source=USD&target=EUR,GBP Authorization: Bearer art_live_... [{"rate":0.914495,"source":"USD","target":"EUR","time":"..."}, {"rate":0.765706,"source":"USD","target":"GBP","time":"..."}] Python
import os, time from decimal import Decimal, ROUND_HALF_EVEN import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry session = requests.Session() session.mount("https://", HTTPAdapter(max_retries=Retry( total=3, backoff_factor=0.5, status_forcelist=[500, 502, 503, 504], allowed_methods=["GET"]))) session.headers["Authorization"] = f"Bearer {os.environ['ALLRATES_KEY']}" _cache: dict[str, tuple[float, dict[str, Decimal]]] = {} def rates(source: str, targets: list[str], ttl: int = 300) -> dict[str, Decimal]: key = f"{source}:{','.join(targets)}" if key in _cache and time.time() - _cache[key][0] < ttl: return _cache[key][1] r = session.get("https://allratestoday.com/api/v1/rates", params={"source": source, "target": ",".join(targets)}, timeout=10) r.raise_for_status() out = {q["target"]: Decimal(str(q["rate"])) for q in r.json()} _cache[key] = (time.time(), out) return out def convert(amount: str, rate: Decimal, places: str = "0.01") -> Decimal: return (Decimal(amount) * rate).quantize(Decimal(places), rounding=ROUND_HALF_EVEN) r = rates("USD", ["EUR", "GBP"]) print(convert("129.99", r["EUR"])) # 118.88 Decimal(str(x)) matters. Decimal(0.914495) carries the binary float error into your money.
Go
package fx import ( "encoding/json" "fmt" "math/big" "net/http" "net/url" "os" "strings" "sync" "time" ) type quote struct { Rate json.Number `json:"rate"` Target string `json:"target"` } var ( client = &http.Client{Timeout: 10 * time.Second} mu sync.Mutex cache = map[string]struct { at time.Time rates map[string]*big.Rat }{} ) func Rates(source string, targets []string) (map[string]*big.Rat, error) { key := source + ":" + strings.Join(targets, ",") mu.Lock() if c, ok := cache[key]; ok && time.Since(c.at) < 5*time.Minute { mu.Unlock() return c.rates, nil } mu.Unlock() q := url.Values{"source": {source}, "target": {strings.Join(targets, ",")}} req, _ := http.NewRequest("GET", "https://allratestoday.com/api/v1/rates?"+q.Encode(), nil) req.Header.Set("Authorization", "Bearer "+os.Getenv("ALLRATES_KEY")) var resp *http.Response var err error for attempt := 0; attempt < 3; attempt++ { // retry only on network errors and 5xx resp, err = client.Do(req) if err == nil && resp.StatusCode < 500 { break } if resp != nil { resp.Body.Close() } time.Sleep(time.Duration(500*(attempt+1)) * time.Millisecond) } if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != 200 { return nil, fmt.Errorf("fx api: %s", resp.Status) } dec := json.NewDecoder(resp.Body) dec.UseNumber() // keep the rate as text, not float64 var qs []quote if err := dec.Decode(&qs); err != nil { return nil, err } out := map[string]*big.Rat{} for _, x := range qs { r, ok := new(big.Rat).SetString(x.Rate.String()) if !ok { return nil, fmt.Errorf("bad rate %q", x.Rate) } out[x.Target] = r } mu.Lock() cache[key] = struct { at time.Time rates map[string]*big.Rat }{time.Now(), out} mu.Unlock() return out, nil } Convert with new(big.Rat).Mul(amount, rate) and format with .FloatString(2). json.Number plus big.Rat keeps the rate exact from the wire to the result.
PHP
<?php function fx_rates(string $source, array $targets, int $ttl = 300): array { $key = 'fx:' . $source . ':' . implode(',', $targets); if (function_exists('apcu_fetch') && ($hit = apcu_fetch($key)) !== false) { return $hit; } $url = 'https://allratestoday.com/api/v1/rates?' . http_build_query(['source' => $source, 'target' => implode(',', $targets)]); for ($attempt = 0; $attempt < 3; $attempt++) { $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('ALLRATES_KEY')], ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($body !== false && $status < 500) break; usleep(500000 * ($attempt + 1)); } if ($status !== 200) throw new RuntimeException("FX API $status"); $out = []; foreach (json_decode($body, true) as $q) { // PHP 7.1+ casts floats to their shortest round-trip string ("0.914495"), safe for bcmath $out[$q['target']] = (string) $q['rate']; } if (function_exists('apcu_store')) apcu_store($key, $out, $ttl); return $out; } $r = fx_rates('USD', ['EUR', 'GBP']); echo bcmul('129.99', $r['EUR'], 2), PHP_EOL; // 118.87 (bcmul truncates; round yourself if needed) bcmul on strings avoids float rounding. It truncates rather than rounds, so add your own rounding rule if the business needs half-up or banker's rounding.
Same rules everywhere
- Timeout and bounded retries on
5xxonly. A401(bad key) or429(quota) won't fix itself by retrying. - Cache 1–15 minutes. The data changes every 60 seconds.
- Batch targets. One call per base currency, not one per pair.
- Exact decimals.
Decimal,big.Ratandbcmath, never binary floats for money.
Links
- Free API key: https://allratestoday.com/register/
- API docs: https://allratestoday.com/developers/
- Official central bank rates on the same key: https://allratestoday.com/central-bank-rates-api/
Rates by AllRatesToday.

