Skip to content

BACEN Service

Some free exchange-rate APIs block requests that come from cloud providers: the service answers on your laptop and fails once it runs on AWS. The PTAX of the Central Bank of Brazil (BCB, Banco Central do Brasil) is a public API, with no key and no sign-up, that quotes every major currency in Brazilian reals (BRL). This page gives the whole exchange microservice, in Python with FastAPI, backed by PTAX: your job is the container and wiring it into the platform.

Learning objectives

After this page you should be able to:

  • Containerize a Python service managed by uv, with a reproducible lock file.
  • Integrate a new microservice into the Compose stack and behind the gateway.
  • Explain how a cross rate (USD → EUR) comes out of quotes that are all in BRL.

Optional

Using this service is an option of the Exchange API exercise: you may still write your own service on any third-party API. If you take this one, say so in your repository's README.

How it works

The gateway resolves who is calling and forwards the request with the id-account header. The service asks PTAX for the latest quote of each currency in BRL (the last 7 days, since weekends and holidays have no quote), keeps it in memory for 5 minutes and divides one by the other. Only one request per currency refreshes the cache at a time: the others wait for it instead of all calling the BCB together. When PTAX fails and an old rate is in memory, the service answers with it.

sequenceDiagram
    participant G as gateway
    participant E as exchange
    participant P as PTAX (BCB)
    G->>E: GET /exchange/USD/EUR + id-account
    E->>P: CotacaoMoedaPeriodo USD, last 7 days
    P-->>E: buy/sell in BRL, every bulletin
    E->>P: CotacaoMoedaPeriodo EUR, last 7 days
    P-->>E: buy/sell in BRL, every bulletin
    E->>E: cross rate through BRL, cache 5 min
    E-->>G: {"sell", "buy", "date", "id-account"}

PTAX only quotes against the real, so USD → EUR goes through BRL. With \(c\) (buy) and \(v\) (sell) the PTAX quotes in BRL:

\[ \text{buy} = \frac{c_\text{USD}}{v_\text{EUR}} \qquad\qquad \text{sell} = \frac{v_\text{USD}}{c_\text{EUR}} \]

buy is what the market pays for 1 USD, in euros (it buys your dollars and sells you euros); sell is what it charges. BRL itself counts as 1, so GET /exchange/USD/BRL is the PTAX quote of the dollar.

The project

exchange/
├── pyproject.toml
├── uv.lock          # created by uv lock: commit it
└── main.py
1
2
3
4
5
6
7
8
9
[project]
name = "exchange"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
    "fastapi>=0.115",
    "httpx>=0.27",
    "uvicorn[standard]>=0.30",
]
"""Exchange service: currency rates from the Central Bank of Brazil (PTAX)."""

import asyncio
import os
import time
from collections import defaultdict
from contextlib import asynccontextmanager
from datetime import date, timedelta

import httpx
from fastapi import FastAPI, Header, HTTPException, Response

PTAX_URL = os.getenv("PTAX_URL", "https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata")
PTAX_TIMEOUT = float(os.getenv("PTAX_TIMEOUT", "3"))  # seconds: never wait longer than the caller would
CACHE_SECONDS = float(os.getenv("CACHE_SECONDS", "300"))  # PTAX publishes a few bulletins a day
RETRY_SECONDS = float(os.getenv("RETRY_SECONDS", "30"))  # after a failed refresh, serve stale this long
# currency -> (valid until, quote, how a request served from it is labelled: "hit" or "stale")
_cache: dict[str, tuple[float, dict, str]] = {}
_locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock)


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with httpx.AsyncClient(timeout=PTAX_TIMEOUT) as client:
        app.state.client = client
        yield


app = FastAPI(title="exchange", lifespan=lifespan)


async def brl_quote(currency: str) -> tuple[dict, str]:
    """Latest PTAX quote of a currency in BRL ({"buy", "sell", "date"}) and where it came from."""
    if currency == "BRL":
        return {"buy": 1.0, "sell": 1.0, "date": None}, "hit"
    cached = _cache.get(currency)
    if cached and time.monotonic() < cached[0]:
        return cached[1], cached[2]
    # one refresh per currency at a time: the requests that arrive meanwhile wait for it
    # instead of all calling PTAX together (a stampede on a provider we do not own)
    async with _locks[currency]:
        cached = _cache.get(currency)
        if cached and time.monotonic() < cached[0]:
            return cached[1], cached[2]
        return await _refresh(currency, cached)


async def _refresh(currency: str, cached: tuple[float, dict, str] | None) -> tuple[dict, str]:
    # a 7-day window always holds a business day (weekends and holidays have no PTAX)
    end = date.today()
    start = end - timedelta(days=7)
    url = (
        f"{PTAX_URL}/CotacaoMoedaPeriodo(moeda=@moeda,dataInicial=@dataInicial,dataFinalCotacao=@dataFinalCotacao)"
        f"?@moeda='{currency}'&@dataInicial='{start:%m-%d-%Y}'&@dataFinalCotacao='{end:%m-%d-%Y}'"
        "&$format=json&$select=cotacaoCompra,cotacaoVenda,dataHoraCotacao"
    )
    try:
        response = await app.state.client.get(url)
        response.raise_for_status()
        rows = response.json()["value"]
    except (httpx.HTTPError, KeyError, ValueError) as e:
        if cached:  # BCB is slow, down or blocking us: an old rate beats an error
            _cache[currency] = (time.monotonic() + RETRY_SECONDS, cached[1], "stale")
            return cached[1], "stale"
        raise HTTPException(status_code=502, detail=f"PTAX unavailable: {e!r}") from e
    if not rows:
        raise HTTPException(status_code=404, detail=f"Unknown currency: {currency}")

    last = rows[-1]  # rows come in time order: the latest bulletin is the last one
    quote = {
        "buy": last["cotacaoCompra"],
        "sell": last["cotacaoVenda"],
        "date": last["dataHoraCotacao"][:19],
    }
    _cache[currency] = (time.monotonic() + CACHE_SECONDS, quote, "hit")
    return quote, "miss"


@app.get("/exchange/{source}/{target}")
@app.get("/exchanges/{source}/{target}", include_in_schema=False)
async def exchange(
    source: str,
    target: str,
    response: Response,
    id_account: str = Header(alias="id-account"),
):
    """Rate to convert 1 unit of `source` into `target` (e.g. USD → EUR)."""
    src, src_from = await brl_quote(source.upper())
    tgt, tgt_from = await brl_quote(target.upper())
    # X-Cache: miss if PTAX was called, stale if an expired rate was served, hit otherwise
    froms = {src_from, tgt_from}
    response.headers["X-Cache"] = "miss" if "miss" in froms else "stale" if "stale" in froms else "hit"
    # PTAX quotes every currency in BRL, so the cross rate goes through BRL:
    # buy  = what the market pays for 1 `source`, in `target` (it buys source, sells target)
    # sell = what the market charges for 1 `source`, in `target` (it sells source, buys target)
    return {
        "sell": round(src["sell"] / tgt["buy"], 6),
        "buy": round(src["buy"] / tgt["sell"], 6),
        "date": src["date"] or tgt["date"],
        "id-account": id_account,
    }


@app.get("/exchange/currencies")
async def currencies():
    """Currencies PTAX quotes (besides BRL)."""
    try:
        response = await app.state.client.get(f"{PTAX_URL}/Moedas?$format=json&$select=simbolo,nomeFormatado")
        response.raise_for_status()
    except httpx.HTTPError as e:
        raise HTTPException(status_code=502, detail=f"PTAX unavailable: {e!r}") from e
    return [{"symbol": m["simbolo"], "name": m["nomeFormatado"]} for m in response.json()["value"]]


@app.get("/health")
async def health():
    return {"status": "ok"}
Endpoint Returns
GET /exchange/{from}/{to} the rate from one currency to another (also answers on /exchanges/..., as the exercise statement spells it)
GET /exchange/currencies the currencies PTAX quotes, besides BRL
GET /health {"status": "ok"}, for the container health check

Every rate response carries the header X-Cache: miss (PTAX was called), hit (rate from memory) or stale (PTAX failed and an expired rate was served). The settings come from environment variables, so the container changes them without a new image:

Variable Default What it sets
PTAX_URL the BCB address base URL of the PTAX API
PTAX_TIMEOUT 3 seconds to wait for PTAX
CACHE_SECONDS 300 how long a rate is reused before asking PTAX again
RETRY_SECONDS 30 after a failed call, how long the old rate is served before trying again

Run it locally

In the exchange/ folder:

uv lock                                   # creates uv.lock from pyproject.toml
uv run uvicorn main:app --reload --port 8000

In another terminal:

curl -H "id-account: 0195ae95-5be7-7dd3-b35d-7a7d87c404fb" localhost:8000/exchange/USD/EUR

You should see something like:

{"sell":0.906885,"buy":0.9066,"date":"2026-11-13 13:03:27","id-account":"0195ae95-5be7-7dd3-b35d-7a7d87c404fb"}

The date is the PTAX bulletin used: on a weekend or before 10 a.m. (Brasília) it is the last business day. Without the header the service answers 422; an unknown currency (/exchange/XYZ/BRL) answers 404.

Your task: the container

  1. Write the Dockerfile of the service:
    • base image python:3.12-slim, with the uv binary copied from ghcr.io/astral-sh/uv1;
    • copy pyproject.toml and uv.lock before main.py and run uv sync --frozen, so a code change does not reinstall the dependencies;
    • start uvicorn main:app on 0.0.0.0:8000.
  2. Add the service exchange to the platform's compose.yaml (no port published: only the gateway reaches it).
  3. Add the gateway route Path=/exchange/** → http://exchange:8000, behind authentication like the other business routes.
  4. Check it through the gateway: log in, then GET /exchange/USD/EUR with the token returns the rate and your id-account.
  5. In the cloud: from a pod of the cluster, curl the PTAX URL once to confirm the provider answers from AWS.

Limits of PTAX

  • Quotes only exist on business days, between about 10 a.m. and 1 p.m. (Brasília); outside that window the service returns the last bulletin.
  • The cache lives in the process memory: a restarted container asks PTAX again, and if BCB does not answer and there is no cached rate the service answers 502.
  • PTAX is a public service of the BCB: do not load test it. Keep the cache on; a load test against your gateway should cause only a handful of calls to PTAX (count the X-Cache: miss).