Gold Price API: How to Get XAU and XAG Rates in Any Currency

5 min read

Gold Price API: How to Get XAU and XAG Rates in Any Currency

A gold price API gives you the price of gold as a number your code can use, usually quoted the same way as a currency pair. XAU is the code for gold and XAG is the code for silver. The rate for XAU/USD tells you how many US dollars one unit of gold costs, and XAU/EUR tells you the same in euros.

The catch is the unit. By convention, one unit of XAU is one troy ounce, not a gram and not an ordinary ounce. If you show jewelry prices per gram, or sell bullion in a currency nobody quotes directly against gold, you need a little arithmetic around the API call. This article walks through that arithmetic and shows where the common mistakes hide.

What XAU and XAG actually represent

Gold and silver were given currency-style codes in the ISO 4217 standard so that software could treat them like any other asset in a pair. XAU and XAG are the two you will meet most often. In a pair, the base is what you are pricing and the quote is the currency you price it in.

PairReads asExample rate
XAU/USDUSD per 1 troy ounce of gold2650.40
XAU/EUREUR per 1 troy ounce of gold2444.60
XAG/USDUSD per 1 troy ounce of silver31.25

These numbers are illustrations only. Metal prices move all day, so never hard-code one.

Two unit facts matter:

  • A troy ounce is about 31.1034768 grams. An everyday (avoirdupois) ounce is about 28.3495 grams. Mixing them up produces a roughly 10% error.
  • Spot prices are wholesale reference prices for the metal itself. Retail coins, bars and jewelry carry premiums, fabrication costs and taxes on top. A spot rate is data, not a shop price and not advice about buying or selling.

Fetching gold and silver rates

GetRatesAPI treats metals like any other asset. The same endpoints that return fiat and crypto rates return XAU and XAG, and the full list of supported codes shows what is available. Metals refresh every 60 seconds.

A single rate is one request unit:

curl -H "Authorization: ApiKey $GETRATESAPI_KEY" \
  "https://api.getratesapi.com/v1/rates/XAU/USD"

The response has the same shape as any other rate. This one is an example:

{"base":"XAU","quote":"USD","rate":"2650.40","as_of":"2026-01-02T10:00:00Z","status":"fresh","type":"direct"}

Three fields deserve attention. rate is a string, so you can parse it into an exact decimal type instead of a float. as_of is the time of the observation. status is fresh or stale; for fiat and metals a rate turns stale after 5 minutes. Stale rates are flagged, not withheld, so your code decides what to do with them. See the current rate documentation for the full response description.

To price gold in several currencies at once, use the one-base form. Up to 20 quotes cost a single request unit:

curl -H "Authorization: ApiKey $GETRATESAPI_KEY" \
  "https://api.getratesapi.com/v1/rates/XAU?quote=USD,EUR,GBP,JPY,CHF"

If one of the quote codes is not supported, it is listed under unsupported and the rest of the call still succeeds.

Gold in a currency nobody quotes directly

Markets quote gold mainly against the US dollar. A pair like XAU/CZK or XAG/BRL may have no direct market. GetRatesAPI derives the missing pair through USD, EUR or BTC, and marks the rate "type": "derived". The as_of of a derived rate is the oldest of its inputs, so the timestamp never looks fresher than the data behind it.

The idea is the same as in our guide to cross rates: if gold costs 2650.40 USD per ounce and 1 USD buys a certain number of CZK, multiplying the two gives CZK per ounce. You do not need to do this yourself, but it helps to know why a derived rate can lag a direct one by a few seconds.

Converting troy ounces to grams

Most consumer-facing gold prices are per gram, and bullion dealers often list in grams or kilograms. The conversion is one division:

price per gram = price per troy ounce / 31.1034768

Here is a Python example that fetches the ounce price, converts to a per-gram price and values a weight in grams. It uses Decimal end to end, as covered in currency conversion rounding without floating-point errors.

import os
from decimal import Decimal, ROUND_HALF_UP

import requests

GRAMS_PER_TROY_OUNCE = Decimal("31.1034768")
API = "https://api.getratesapi.com/v1"
HEADERS = {"Authorization": f"ApiKey {os.environ['GETRATESAPI_KEY']}"}


def metal_rate(metal: str, currency: str) -> dict:
    resp = requests.get(f"{API}/rates/{metal}/{currency}", headers=HEADERS, timeout=5)
    resp.raise_for_status()
    return resp.json()


def value_of_grams(metal: str, currency: str, grams: str) -> dict:
    data = metal_rate(metal, currency)
    per_ounce = Decimal(data["rate"])
    per_gram = per_ounce / GRAMS_PER_TROY_OUNCE
    total = per_gram * Decimal(grams)
    return {
        "per_gram": per_gram.quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP),
        "total": total.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP),
        "as_of": data["as_of"],
        "status": data["status"],
    }


print(value_of_grams("XAU", "USD", "100"))

With the example rate of 2650.40 USD per ounce, the per-gram price is about 85.2123 USD and 100 grams comes to about 8,521.23 USD. Note where the rounding happens: only at the end, for display. The intermediate per-gram value keeps full precision, so the total is not distorted by rounding twice.

Why not use the convert endpoint?

GET /v1/convert?from=XAU&to=EUR&amount=2.5 is the right tool when the amount is in troy ounces: it returns an exact converted_amount for 2.5 ounces of gold in euros. See the convert documentation. For grams, either convert grams to ounces first or use the rate and divide, as in the code above. Keeping the unit conversion in your own code makes it explicit and easy to test.

Common mistakes with metal prices

  • Using floats. Gold at four-digit prices multiplied by fractional weights compounds tiny binary errors. Parse the string rate into Decimal, BigDecimal or an integer-based money type.
  • Confusing troy and avoirdupois ounces. Define the gram constant once, name it clearly, and cover it with a test.
  • Treating spot as a retail price. If you sell physical metal, add your own premium and tax as separate, visible line items.
  • Ignoring status. If a rate is stale, decide in advance whether to show a "price delayed" note, disable checkout or fall back to the last good value. The caching guide covers these patterns.
  • Expecting an official fixing. The rate is a market observation, not a bank or central-bank fixing. If a contract specifies a particular fixing, take that value from the party named in the contract.
  • Re-fetching on every page view. Metals update every 60 seconds, so caching a rate for 30 to 60 seconds saves request units without making prices noticeably older.

Handling errors cleanly

Match on the code field of the JSON error, never on the message text. A typo such as XAUU returns invalid_asset_symbol with HTTP 400, and malformed requests are not billed. A pair that cannot be priced returns unsupported_pair (404). If you hit the per-second limit you receive rate_limit_exceeded (429) with retry_after_seconds. The error reference lists every code.

Try it with your own pair

Metals, fiat and crypto share one API, so a dashboard that shows gold, silver and Bitcoin in a customer's local currency needs one integration and one authentication header. Create a free account, no credit card needed, and try XAU/USD or XAG/EUR in the dashboard playground. If you outgrow the free quota, the pricing page lists the current plans.

All articles →
Gold Price API: Get XAU and XAG Rates in Any Currency — GetRatesAPI