How to Show Live Gold Prices on a Website with an API
Symbol: Gold price API
You want to show a live “Gold price in USD per troy ounce” on your website and keep it updated automatically. By the end of this guide you’ll have a working snippet that fetches the current XAU price from an API, converts it to USD/oz correctly, and renders it on a page with safeguards for units, caching, and market hours.
What you’ll build: a live XAU/USD widget backed by an API
We’ll integrate an API endpoint that returns the latest gold (XAU) rate, compute “USD per troy ounce,” and render it in your site. We’ll focus on two endpoints relevant to this job:
- Latest Rates: to fetch the current XAU rate, updated depending on your plan.
- Bid/Ask: optional, if you want to display a live spread (useful for trading-style UIs).
We’ll keep it simple and robust, so it fits e-commerce, research dashboards, and trading tools. If you need a deeper catalog of features or symbols, check the Documentation and the always up-to-date Symbols. The API home is here: metals-api.com.
Deciding what price to show: last trade vs. bid/ask mid
On many websites, “gold price” means the latest indicative price per troy ounce in USD. That’s enough for a single headline number or a simple “live price” badge. If you quote or trade, you might also want to show:
- Bid/Ask: show the current best bid and ask and compute a mid-price for display.
- Spread: show the difference between ask and bid, useful for traders and advanced users.
We’ll start with the Latest Rates endpoint to get a clean “USD per troy ounce” value, and note where Bid/Ask fits if you need that detail.
How Metals-API structures gold rates (read this before you code)
Metals-API uses XAU to denote gold. Rates are returned relative to a base currency (by default USD). The key details:
- Base is often USD. In that case, rates like XAU are “troy ounces of gold per 1 USD.”
- To get USD per troy ounce (what most users expect), take the inverse of XAU: USD/XAU = 1 / XAU.
- Some responses also include the inverse pair (USDXAU), which is already “USD per 1 troy ounce.” If it’s present, you can use it directly.
- Units are troy ounces for precious metals. If you display grams, you must convert (1 troy ounce = 31.1034768 grams).
You can verify symbol availability at Metals-API Supported Symbols. We’ll use XAU specifically in all examples.
Step 1 — Get an API key
Sign up to obtain your access_key. You’ll pass it as a query parameter on each request:
Register for your API key. You can always return to the Metals-API homepage to learn more about products and updates.
Step 2 — Fetch the latest gold price (curl)
Use the Latest Rates endpoint to retrieve XAU with USD as base. We also ask for USDXAU explicitly to avoid manual inversion when available.
curl -s 'https://metals-api.com/api/latest?access_key=YOUR_API_KEY&base=USD&symbols=XAU,USD,USDXAU'
Here is an official sample of a valid response you might parse. Use these exact fields to wire your parsing logic:
{"success":true,"timestamp":1795047780,"date":"2026-11-19","base":"USD","rates":{"XAU":0.00026737253014625,"USD":1,"USDXAU":3740.1000000000386}}
What the fields mean for your widget
- success: request status flag.
- timestamp: Unix epoch seconds for the returned rate snapshot. Convert to local time if you display a “last updated” label.
- date: UTC calendar date of the snapshot.
- base: the base currency for the rates (USD here).
- rates.XAU: troy ounces of gold per 1 USD (XAU/USD). To get USD per ounce, invert it: 1 / rates.XAU.
- rates.USDXAU: USD per troy ounce directly (use this if provided).
- rates.USD: the base itself (1).
If your plan or request doesn’t return USDXAU, compute USD per ounce as 1 / XAU. With the sample above: 1 / 0.00026737253014625 ≈ 3740.10 USD per troy ounce (which matches USDXAU).
Step 3 — Render a live number on your website (JavaScript)
The script below fetches the latest XAU quote, prefers USDXAU if present, otherwise inverts XAU. It then updates the DOM with a formatted USD/oz number and a human-readable timestamp.
<div id="gold-price">Loading gold price...</div>
<div id="gold-updated"></div>
<script>
(async function renderGoldPrice() {
const endpoint = 'https://metals-api.com/api/latest';
const params = new URLSearchParams({
access_key: 'YOUR_API_KEY',
base: 'USD',
symbols: 'XAU,USDXAU,USD'
});
try {
const res = await fetch(`${endpoint}?${params.toString()}`, { cache: 'no-store' });
if (!res.ok) throw new Error('Network response was not ok');
const data = await res.json();
if (!data.success || !data.rates) throw new Error('API returned an error');
// Prefer direct USD per ounce (USDXAU) if present; else invert XAU.
let usdPerOunce = data.rates.USDXAU;
if (typeof usdPerOunce !== 'number') {
const xauPerUsd = data.rates.XAU;
if (typeof xauPerUsd !== 'number' || xauPerUsd === 0) {
throw new Error('Missing XAU rate');
}
usdPerOunce = 1 / xauPerUsd;
}
// Format and render
const priceEl = document.getElementById('gold-price');
const updatedEl = document.getElementById('gold-updated');
priceEl.textContent = `$${usdPerOunce.toLocaleString(undefined, { maximumFractionDigits: 2 })} / troy oz`;
const ts = typeof data.timestamp === 'number' ? new Date(data.timestamp * 1000) : new Date();
updatedEl.textContent = `Last updated: ${ts.toLocaleString()}`;
// Optional: Cache in localStorage for quick re-paints between page loads
localStorage.setItem('goldPriceCache', JSON.stringify({ usdPerOunce, timestamp: data.timestamp }));
} catch (err) {
console.error('Failed to load gold price:', err);
// Attempt to recover from cache
const cache = localStorage.getItem('goldPriceCache');
if (cache) {
try {
const { usdPerOunce, timestamp } = JSON.parse(cache);
document.getElementById('gold-price').textContent = `$${usdPerOunce.toLocaleString(undefined, { maximumFractionDigits: 2 })} / troy oz (cached)`;
const ts = typeof timestamp === 'number' ? new Date(timestamp * 1000) : new Date();
document.getElementById('gold-updated').textContent = `Last updated: ${ts.toLocaleString()}`;
} catch (e) {
document.getElementById('gold-price').textContent = 'Unable to load gold price';
}
} else {
document.getElementById('gold-price').textContent = 'Unable to load gold price';
}
}
})();
</script>
Step 4 — Show bid/ask (optional) for trading-style UIs
If you want to show both sides of the market, request the Bid/Ask endpoint for XAU. It returns bid, ask, and spread fields. A typical pattern is:
- Display “mid” = (bid + ask) / 2 for the headline number.
- Show bid and ask in smaller type for transparency and a pro feel.
The Bid/Ask endpoint is most useful if your audience uses the price to trade, quote, or hedge. For site-wide banners or product pricing, the Latest Rates endpoint is usually enough. For request options and field formats, see the Metals-API Documentation.
Units, conversions, and what to display
Gold is quoted in troy ounces (XAU). If your UX requires grams, kilograms, or tolas, convert carefully:
- 1 troy ounce = 31.1034768 grams.
- USD per gram = (USD per troy ounce) / 31.1034768.
- Round to a sensible precision for your audience (e.g., 2 decimals for USD/oz, 3–4 for USD/g).
When building price labels, include the unit explicitly (e.g., “USD / troy oz” or “USD / g”). Ambiguity here is the top cause of mispricing in production.
Handling base currency and inversions correctly
With base=USD, the XAU value you receive is “troy ounces per 1 USD.” To show the common “USD per troy ounce,” do one of:
- Use USDXAU directly if it’s included in the response.
- Compute 1 / XAU to invert ounces-per-dollar into dollars-per-ounce.
Always guard against divide-by-zero and missing fields. If you must support multiple bases or cross conversions, consider the Convert endpoint (see docs) to simplify logic and keep consistent rounding rules across your app.
Update cadence, caching, and market hours
Gold trades nearly around the clock on weekdays via OTC and futures venues; weekends and holidays can be quiet or closed, so the latest timestamp might not change for stretches. Practical guidance:
- Respect your plan’s update frequency. The Latest Rates endpoint updates at intervals that vary by subscription. Polling faster will not yield fresher data and may waste requests.
- Cache responses on the client (localStorage) and/or server for a short TTL (e.g., 30–60 seconds if your plan supports frequent updates; longer if not).
- Display a “Last updated” time using the timestamp field so users understand staleness.
- On weekends/holidays, keep showing the last available price and update the staleness label.
- If you have many pages or users requesting the same price, centralize calls on your server and fan out via your app to reduce API usage.
Error handling and fallbacks that don’t break your layout
- On API errors, show the last cached price with a “(cached)” label and a neutral color.
- Gracefully handle null/undefined fields and avoid NaN outputs in the UI.
- If you compute 1 / XAU, ensure XAU is a positive finite number before inverting.
- Defer DOM updates until you have a parsed, validated number.
Security and deployment notes
- For public websites, prefer calling the API from your server to keep your access_key private and to apply rate-limiting and caching once per edge location.
- If you must call from the browser, rotate keys periodically and consider origin restrictions if available. Never expose admin credentials.
- Handle CORS appropriately if you proxy via your backend.
Testing your integration
- Log raw responses in development and verify fields: base, timestamp, rates.XAU, rates.USDXAU.
- Simulate missing USDXAU and confirm the inverse path formats correctly.
- Switch your device clock/timezone to check “Last updated” renders as expected.
- Throttle network and verify your cached fallback path keeps the page usable.
Extending your widget
- Historical sparkline: query the Time-Series endpoint for XAU and draw a mini chart. Useful for “up/down today” context.
- Daily OHLC: show open/high/low/close if you want a compact market summary beneath the headline price.
- Carat pricing: if you sell jewelry, look into gold-by-carat endpoints to map USD/oz to retail geometries.
For specifics on request parameters, field structures, and additional endpoints like intraday or WebSocket streaming, consult the Documentation. For broader program and connectivity information, see MCP.
Data and UX tips that save time
- Rounding: round for display, but keep the unrounded value in memory if you’ll do further math (e.g., conversions to grams or carats).
- Locale: use locale-aware formatting for thousands separators and decimals; USD typically shows 2 decimals, but you might use more in research tools.
- Accessibility: include the unit in the aria-label (e.g., “Gold price, USD per troy ounce”).
- Latency: render the last cached value immediately, then refresh in the background. This avoids layout shift.
Why XAU matters in modern apps
Gold (XAU) sits at the intersection of macro hedging, jewelry manufacturing, and digital asset infrastructure. Reliable programmatic access to live and historical XAU feeds underpins everything from spot-pricing in e-commerce to risk dashboards in trading. Metals-API gives you both the raw rate and the standardized unit (troy ounces) so you can compose accurate pricing, analytics, and alerts in your stack without bespoke scrapers or patchwork data sources.
With clean JSON and consistent symbols, you can treat XAU like any other data stream: cache, normalize, enrich, and route it into your UI, pricing rules, or quant models. If you plan to add more instruments later, refer to the full Symbols list for coverage.
FAQ
How often should I refresh the gold price?
Poll at or slightly below your plan’s update interval. If your plan updates every N minutes, add a small buffer (e.g., N + 10%) and cache on your server to avoid redundant requests.
Why is the XAU number so small when base=USD?
Because it’s “troy ounces per 1 USD.” Invert it to get “USD per troy ounce,” or use the USDXAU field if present.
What timezone are the dates/timestamps in?
The date is UTC; the timestamp is Unix epoch seconds. Convert to local time in your UI if needed.
How should I handle weekends and holidays?
Expect the timestamp to advance slowly or not at all during closures. Keep showing the last rate with a clear “Last updated” label. Consider a lighter color or “market closed” note.
Can I show grams instead of troy ounces?
Yes. Convert: USD/g = (USD/oz) / 31.1034768. Label the unit clearly.
If you’re ready to wire your site to live gold pricing, get your access key now: Register. Then plug into the Documentation and metals-api.com homepage for implementation details and updates.