Your site needs exchange rates in two places: a JSON endpoint for your own frontend, and a server-rendered page that shows a small rate table. Calling the upstream API on every request is slow and burns quota. This post builds both on FastAPI with one cached source of truth.
Stack: Python 3.12+, FastAPI, httpx, Jinja2, Babel for currency formatting, and HTMX on the page.
pip install "fastapi[standard]" httpx jinja2 babel
The rate source
We use AllRatesToday for live mid-market rates. Get a free API key and export it:
export ALLRATES_API_KEY=art_live_xxxxxxxx
The upstream call looks like this:
GET https://allratestoday.com/api/v1/rates?source=USD&target=EUR,GBP,JPY
Authorization: Bearer art_live_xxxxxxxx
It returns a JSON array, one object per target:
[
{"rate": 0.92, "source": "USD", "target": "EUR", "time": "2026-12-06T10:15:00Z"},
{"rate": 0.79, "source": "USD", "target": "GBP", "time": "2026-12-06T10:15:00Z"}
]
All targets in one call count as one request, so we always batch.
One httpx client for the whole app
Creating an httpx.AsyncClient per request throws away connection pooling. Create it once in the lifespan handler and close it on shutdown.
# app/main.py
import os
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI
from app.rates import RateCache
@asynccontextmanager
async def lifespan(app: FastAPI):
async with httpx.AsyncClient(
base_url="https://allratestoday.com",
headers={"Authorization": f"Bearer {os.environ['ALLRATES_API_KEY']}"},
timeout=httpx.Timeout(5.0),
) as client:
app.state.rates = RateCache(client, ttl_seconds=600)
yield
app = FastAPI(lifespan=lifespan)
A TTL cache that does not stampede
A plain dict with timestamps works until the entry expires and 40 concurrent requests all miss at once. An asyncio.Lock per key fixes that: the first request fetches, the others wait and then read the fresh value.
# app/rates.py
import asyncio
import logging
import time
import httpx
log = logging.getLogger(__name__)
class RateCache:
def __init__(self, client: httpx.AsyncClient, ttl_seconds: int = 600):
self.client = client
self.ttl = ttl_seconds
self._entries: dict[str, tuple[float, dict]] = {}
self._locks: dict[str, asyncio.Lock] = {}
def _fresh(self, key: str) -> dict | None:
entry = self._entries.get(key)
if entry and time.monotonic() - entry[0] < self.ttl:
return entry[1]
return None
async def get(self, base: str, targets: tuple[str, ...]) -> dict:
key = f"{base}:{','.join(sorted(targets))}"
if (hit := self._fresh(key)) is not None:
return hit
lock = self._locks.setdefault(key, asyncio.Lock())
async with lock:
# Another task may have refreshed it while we waited.
if (hit := self._fresh(key)) is not None:
return hit
try:
data = await self._fetch(base, targets)
except httpx.HTTPError as exc:
stale = self._entries.get(key)
if stale:
log.warning("rates fetch failed (%s); serving stale data", exc)
return stale[1]
raise
self._entries[key] = (time.monotonic(), data)
return data
async def _fetch(self, base: str, targets: tuple[str, ...]) -> dict:
resp = await self.client.get(
"/api/v1/rates",
params={"source": base, "target": ",".join(targets)},
)
resp.raise_for_status()
rows = resp.json()
return {
"base": base,
"time": max(row["time"] for row in rows),
"rates": {row["target"]: row["rate"] for row in rows},
}
Notes:
-
time.monotonic()is immune to clock changes, which matters for TTL math. -
raise_for_status()raiseshttpx.HTTPStatusError, a subclass ofhttpx.HTTPError, so timeouts, connection errors, 401 and 429 all go through the same stale-fallback path. - Ten minutes is a sensible TTL for display prices. Rates upstream refresh about every 60 seconds; nobody needs that on a product page.
The JSON endpoint
Validate the input, map upstream failures to sensible status codes, and send a Cache-Control header so browsers and CDNs can help.
# app/main.py (continued)
from typing import Annotated
from fastapi import HTTPException, Query, Request, Response
SUPPORTED = ("USD", "EUR", "GBP", "JPY", "CAD", "AUD", "CHF", "INR")
@app.get("/api/rates")
async def rates(
request: Request,
response: Response,
base: Annotated[str, Query(pattern="^[A-Za-z]{3}$")] = "USD",
):
base = base.upper()
if base not in SUPPORTED:
raise HTTPException(400, f"Unsupported base currency {base}")
targets = tuple(c for c in SUPPORTED if c != base)
try:
data = await request.app.state.rates.get(base, targets)
except httpx.HTTPStatusError as exc:
if exc.response.status_code == 401:
# Our key is wrong. That is our bug, not the client's.
raise HTTPException(502, "Rate provider rejected our credentials")
if exc.response.status_code == 429:
raise HTTPException(503, "Rates temporarily unavailable", headers={"Retry-After": "60"})
raise HTTPException(502, "Rate provider error")
except httpx.HTTPError:
raise HTTPException(504, "Rate provider timed out")
response.headers["Cache-Control"] = "public, max-age=60"
return data
Try it:
fastapi dev app/main.py
curl -s localhost:8000/api/rates?base=EUR | python -m json.tool
Your frontend now calls /api/rates on your own domain. The API key never leaves the server, which is required anyway: the keyed AllRatesToday API sends no CORS headers.
Locale-aware formatting in Jinja
Python has no built-in Intl.NumberFormat, but Babel does the same job using CLDR data. Register it as a Jinja filter:
# app/main.py (continued)
from babel.numbers import format_currency
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates(directory="app/templates")
LOCALE_FOR = {"USD": "en_US", "EUR": "de_DE", "GBP": "en_GB", "JPY": "ja_JP",
"CAD": "en_CA", "AUD": "en_AU", "CHF": "de_CH", "INR": "en_IN"}
def money(amount: float, currency: str) -> str:
return format_currency(amount, currency, locale=LOCALE_FOR.get(currency, "en_US"))
templates.env.filters["money"] = money
money(1234.56, "JPY") gives ¥1,235 and money(1234.56, "EUR") gives 1.234,56 €. Babel knows each currency's decimal places, so you do not hardcode them.
An HTMX page that refreshes the rate table
The page renders the table on the server. HTMX then re-requests only the table fragment every 10 minutes, so a tab left open does not show stale numbers.
# app/main.py (continued)
from fastapi.responses import HTMLResponse
async def table_context(request: Request, amount: float) -> dict:
targets = tuple(c for c in SUPPORTED if c != "USD")
try:
data = await request.app.state.rates.get("USD", targets)
except httpx.HTTPError:
data = None
return {"data": data, "amount": amount}
@app.get("/", response_class=HTMLResponse)
async def home(request: Request, amount: float = 100):
ctx = await table_context(request, amount)
return templates.TemplateResponse(request, "index.html", ctx)
@app.get("/fragments/rate-table", response_class=HTMLResponse)
async def rate_table(request: Request, amount: float = 100):
ctx = await table_context(request, amount)
return templates.TemplateResponse(request, "_rate_table.html", ctx)
<!-- app/templates/index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Prices in your currency</title>
<script src="https://unpkg.com/htmx.org@2.0.4"></script>
</head>
<body>
<label>
Amount in USD
<input type="number" name="amount" value="{{ amount }}" min="0" step="0.01"
hx-get="/fragments/rate-table"
hx-trigger="input changed delay:400ms"
hx-target="#rate-table" hx-swap="outerHTML">
</label>
{% include "_rate_table.html" %}
</body>
</html>
<!-- app/templates/_rate_table.html -->
<div id="rate-table"
hx-get="/fragments/rate-table?amount={{ amount }}"
hx-trigger="every 600s"
hx-swap="outerHTML">
{% if data %}
<table>
<tr><th>Currency</th><th>Converted</th></tr>
{% for code, rate in data.rates.items() %}
<tr><td>{{ code }}</td><td>{{ (amount * rate) | money(code) }}</td></tr>
{% endfor %}
</table>
<small>Live mid-market rates as of {{ data.time }}</small>
{% else %}
<p>Rates are unavailable right now. Please try again in a minute.</p>
{% endif %}
</div>
Each swap replaces the whole div, including its hx-get URL, so the polling request always carries the latest amount. The input uses delay:400ms so typing does not fire a request per keystroke. Every fragment request hits the in-process cache, not the upstream API.
Running more than one worker
The cache lives in process memory. With uvicorn --workers 4 you get four caches and up to four upstream calls per TTL window. That is fine. If you scale out wide, put the same logic in front of Redis. The response fields are documented in the API reference.
FAQ
Why not use functools.lru_cache?
It has no TTL and does not work on coroutines the way you want: it caches the coroutine object, not the result.
Can I use async-lru or cachetools instead?
Yes. The hand-written class is shown so the lock and the stale fallback are visible. Keep both behaviors if you switch.
Should the HTMX fragment be cached by the browser?
No. Leave it uncached so the 10-minute poll always reaches your server. The server-side cache already protects the upstream API.
What about Babel on Python 3.13?
Babel supports current Python versions. If you deploy in a slim container, Babel ships its own CLDR data, so no system locales are needed.
Top comments (0)