Python Currency Converter: Get Live Exchange Rates with Exact Decimals
5 min read
A Python currency converter needs three things: a source of live exchange rates, exact decimal arithmetic, and sensible handling of the cases where the rate is old or the request fails. The HTTP call is the easy part. Most bugs come from using float for money and from ignoring what the API tells you about freshness.
This guide builds a small, production-minded converter with requests and the standard library's decimal module. It fetches a rate, converts an amount, rounds for display, and reacts to stale data and error codes. The pattern works in any framework, whether you are in Django, FastAPI, a Celery job or a plain script.
Why float is the wrong type for a Python currency converter
Python floats are binary approximations. They cannot represent most decimal fractions exactly, and the error shows up in money:
>>> 0.1 + 0.2
0.30000000000000004
>>> from decimal import Decimal
>>> Decimal("0.1") + Decimal("0.2")
Decimal('0.3')
One bad addition is harmless. A million of them across invoices, refunds and ledger totals is a reconciliation problem. The rule is simple: parse amounts and rates from strings into Decimal, do all math in Decimal, and round once at the end.
A common trap is building a Decimal from a float. Decimal(0.1) captures the float's binary error (0.1000000000000000055511151231257827...). Always pass a string: Decimal("0.1").
This is why GetRatesAPI returns rates and amounts as JSON strings and does not round results. The string goes straight into Decimal with no float in between. For a deeper look at rounding policy, see currency conversion rounding without floating-point errors.
Fetch a live rate
Create an API key in the dashboard and keep it in an environment variable. Requests authenticate with the header Authorization: ApiKey YOUR_API_KEY. The current rate endpoint is GET /v1/rates/{base}/{quote} and returns:
{"base":"EUR","quote":"USD","rate":"1.0842","as_of":"2026-01-02T10:00:00Z","status":"fresh","type":"direct"}
Here is a small client. It reuses one Session, sets a timeout, retries only the errors that are worth retrying, and raises a typed exception for everything else:
import os
import time
from decimal import Decimal
import requests
BASE_URL = "https://api.getratesapi.com"
session = requests.Session()
session.headers.update(
{"Authorization": f"ApiKey {os.environ['GETRATESAPI_KEY']}"}
)
class RatesApiError(Exception):
def __init__(self, http_status, code, message, request_id=None):
super().__init__(f"{code}: {message} (request_id={request_id})")
self.http_status = http_status
self.code = code
self.request_id = request_id
RETRYABLE = {"rate_limit_exceeded", "temporarily_unavailable"}
def call(path, params=None, retries=2):
for attempt in range(retries + 1):
resp = session.get(f"{BASE_URL}{path}", params=params, timeout=5)
if resp.ok:
return resp.json()
try:
body = resp.json()
except ValueError:
body = {}
code = body.get("code", "unknown_error")
if code in RETRYABLE and attempt < retries:
time.sleep(body.get("retry_after_seconds", 2 ** attempt))
continue
raise RatesApiError(
resp.status_code, code, body.get("message", ""), body.get("request_id")
)
def get_rate(base, quote):
data = call(f"/v1/rates/{base}/{quote}")
return {
"rate": Decimal(data["rate"]),
"as_of": data["as_of"],
"status": data["status"],
"type": data["type"],
}
Notice that the code matches on the code field of the error body, never on the human-readable message, which can change. The full list of codes is in the error reference. Retries on 429 deserve their own care; the article on handling rate limits and retries covers backoff and jitter in more depth.
Convert an amount and round at the edge
You have two options for converting. You can fetch the rate and multiply yourself, or you can call the convert endpoint, GET /v1/convert?from=USD&to=EUR&amount=125.50, which returns an exact converted_amount.
Use the convert endpoint when you need one answer. Fetch the rate yourself when you must store it next to the transaction, for example on an invoice, or apply many amounts to one rate.
from decimal import Decimal, ROUND_HALF_UP
# Minor-unit digits per currency (ISO 4217). Extend for the currencies you support.
MINOR_UNITS = {"USD": 2, "EUR": 2, "GBP": 2, "JPY": 0, "KWD": 3}
def to_money(amount, currency):
step = Decimal(1).scaleb(-MINOR_UNITS[currency]) # 0.01, 1, 0.001 ...
return amount.quantize(step, rounding=ROUND_HALF_UP)
def convert(amount, from_code, to_code):
data = call(
"/v1/convert",
params={"from": from_code, "to": to_code, "amount": str(amount)},
)
return Decimal(data["converted_amount"])
Pass the amount as a string (str(Decimal("125.50"))), not a float, so nothing is lost on the way out.
A worked example with the multiply-it-yourself approach, using an illustrative rate of 0.9213 (not a live quote):
amount = Decimal("125.50")
rate = Decimal("0.9213") # example value only
exact = amount * rate # Decimal('115.62315')
print(to_money(exact, "EUR")) # Decimal('115.62')
The exact product keeps every digit. Rounding happens once, in to_money, using the currency's minor units. Which rounding mode you use (half up, half even) is a business or legal policy decision. Pick one, document it, and apply it everywhere.
Two rules keep totals correct:
- Never round intermediate values. Round the final amount you show or charge.
- Store the exact rate string and the rounded amount you actually charged. Do not recompute old transactions from a new rate.
Check freshness before you trust a rate
Every rate carries as_of, the time of the observation, and status, either fresh or stale. Crypto is stale after 1 minute and fiat after 5 minutes. Stale rates are flagged, not withheld, so the decision about what to do is yours.
A reasonable policy depends on the use case:
| Use case | Stale rate behavior |
|---|---|
| Price display on a product page | Show it, optionally with an "approximate" label |
| Checkout total the customer will pay | Refetch once; if still stale, log it and decide by policy |
| Invoice or ledger entry | Record as_of and status with the rate so an auditor can see them |
| Dashboard | Show a "last updated" time from as_of |
In code, it is a few lines:
import logging
log = logging.getLogger("fx")
def get_fresh_rate(base, quote):
result = get_rate(base, quote)
if result["status"] == "stale":
log.warning("Stale rate %s/%s as_of=%s", base, quote, result["as_of"])
result = get_rate(base, quote) # one refetch
return result
Also check type. A rate marked derived was calculated through USD, EUR or BTC because no market quotes the pair directly, and its as_of is the oldest input. That is expected and useful: any pair works, including something like NOK/THB. If you want to understand the math, read cross rates explained.
Handle errors and avoid wasting requests
Wrap the call where you can show the user something useful:
try:
total = to_money(convert(Decimal("125.50"), "USD", "EUR"), "EUR")
except RatesApiError as err:
if err.code in ("invalid_asset_symbol", "invalid_amount"):
... # bad input: fix the request, do not retry
elif err.code == "unsupported_pair":
... # hide this currency option
elif err.code == "quota_exceeded":
... # alert your team; retries will not help
else:
raise
A few habits that save quota:
- Cache briefly. Fiat rates refresh every 60 seconds and crypto every 10 seconds, so polling faster than that returns nothing new. See how to cache exchange rates without showing stale prices.
- Batch quotes.
GET /v1/rates/USD?quote=EUR,GBP,JPYreturns up to 20 quotes against one base for a single request unit. Unsupported quotes are listed in anunsupportedfield instead of failing the call. - Use the free catalog.
GET /v1/assets,/v1/assets/fiatand/v1/assets/cryptolist supported codes and are not billed. Validate currency codes against them before spending units. - Watch usage.
GET /v1/account/usagereturns the period, used, quota and remaining units.
Malformed and rate-limited requests are not billed, so a bug in your input handling will not burn your monthly quota.
Put it together
A minimal command-line converter built from the pieces above:
import sys
from decimal import Decimal
if __name__ == "__main__":
amount = Decimal(sys.argv[1])
src, dst = sys.argv[2].upper(), sys.argv[3].upper()
quote = get_fresh_rate(src, dst)
exact = amount * quote["rate"]
print(f"{amount} {src} = {to_money(exact, dst)} {dst}")
print(f"rate {quote['rate']} ({quote['type']}, {quote['status']}, as of {quote['as_of']})")
Run it with python convert.py 125.50 USD EUR. Because it uses the same rate you display, you can store that rate with the order and reproduce the number later.
Try it with a free key
GetRatesAPI covers about 170 world currencies, gold and silver, and thousands of crypto assets through one REST API, so the same client handles USD/EUR, XAU/USD and BTC/USD. Sign up for a free plan with no credit card, try each endpoint in the dashboard playground, then drop your key into the snippets above.