Live data
Gold Price API
Real-time gold spot prices in 1,000+ currencies.
This tutorial builds a small Python widget that shows live gold, silver, platinum and palladium prices on your website. It uses the same data as Metal Sentinel's gold price API and silver price API. You will get an API key, write a short client module that caches responses so the widget stays within the free plan, and serve the result from a Flask app.
If you only need a price box and don't want to write code, the free embeddable widgets work with one line of HTML and no API key. Build your own when you want your own markup or need the numbers for calculations. If your site runs on PHP, the PHP version of this tutorial builds the same widget.
You need Python 3.9 or newer and two packages, Flask and Requests. The client module only needs Requests, so you can also use it in Django, FastAPI or a plain script.
1. Get your API key
Metal Sentinel keys are issued through RapidAPI.
Create a free account at RapidAPI.
Open the Metal Sentinel plans on RapidAPI and subscribe to one. The Free plan gives you 7,500 requests per month, which is enough for a cached widget, and it doesn't ask for a credit card. The pricing page compares all four plans.
Open the Playground tab. The request headers on the right show your key in
X-RapidAPI-Key. Copy it.
Every request needs two headers:
X-RapidAPI-Key: YOUR_RAPIDAPI_KEY
X-RapidAPI-Host: metal-sentinel.p.rapidapi.com
Your key is tied to your billing. Keep it on the server and never put it in JavaScript that runs in the browser.
2. Test one request
Check that the key works before writing any Python:
curl "https://metal-sentinel.p.rapidapi.com/api/metal-quote?symbol=AU¤cy=USD" \
-H "X-RapidAPI-Key: YOUR_RAPIDAPI_KEY" \
-H "X-RapidAPI-Host: metal-sentinel.p.rapidapi.com"
You get JSON like this:
{
"ID": 1794513653,
"results": [
{
"symbol": "AU",
"currency": "USD",
"ask": 3885.7,
"mid": 3884.7,
"bid": 3883.7,
"high": 4001.2,
"low": 3852.1,
"change": -103.3,
"changePercentage": -2.59,
"unit": "OUNCE",
"timestamp": 1794513600
}
]
}
Notes on the response:
resultsis a list. The quote is inresults[0].midis the spot price per troy ounce.bidandaskare the two sides of the market.changeandchangePercentagecompare the price with the previous close.timestampis a Unix timestamp in seconds.
If something is wrong, for example an unknown symbol, the body has an error key instead:
{ "error": "The selected symbol is invalid." }
Most errors come back with HTTP status 200, so check the body for error in your code.
Supported metal symbols:
Symbol | Metal | Symbol | Metal |
|---|---|---|---|
| Gold |
| Copper |
| Silver |
| Nickel |
| Platinum |
| Aluminum |
| Palladium |
| Lead |
| Rhodium |
| Zinc |
For currency you can use USD, EUR, GBP, CHF, JPY and other ISO codes. Call /api/allowed-currencies for the full list.
3. Project layout
Create these files:
your-site/
├── metal_sentinel.py (the small client module)
├── app.py (the Flask app)
├── cache/ (created on the first request, must be writable)
└── templates/
└── widget.html (the widget template)
The API key goes into an environment variable in the next step, so none of these files contains it.
4. Install the packages and store the key
python -m venv venv
source venv/bin/activate
pip install flask requests
export METAL_SENTINEL_KEY="YOUR_RAPIDAPI_KEY"
On Windows, activate with venv\Scripts\activate and set the key with set METAL_SENTINEL_KEY=YOUR_RAPIDAPI_KEY. On a server, set the variable in your hosting panel or in the service configuration. The code reads the key from the environment, so it never ends up in Git.
5. The client module
metal_sentinel.py sends the request, checks for errors and caches each response in a file. Because of the cache, all visitors share the same data, and your request count doesn't grow with your traffic. A dictionary in memory would be lost on every restart, and each worker process would keep its own copy, so the module uses files.
import hashlib
import json
import os
import time
from pathlib import Path
import requests
HOST = "metal-sentinel.p.rapidapi.com"
class MetalSentinelError(Exception):
"""Raised when the API cannot return usable data."""
class MetalSentinelClient:
def __init__(self, api_key, cache_dir="cache", cache_seconds=1800):
self.api_key = api_key
self.cache_dir = Path(cache_dir)
self.cache_seconds = cache_seconds
self.cache_dir.mkdir(parents=True, exist_ok=True)
def metal_quote(self, symbol, currency="USD"):
"""Live spot quote for one metal, e.g. metal_quote("AU", "USD")."""
data = self._get(
"/api/metal-quote",
{"symbol": symbol.upper(), "currency": currency.upper()},
)
results = data.get("results") or []
if not results:
raise MetalSentinelError(f"No quote returned for {symbol}.")
return results[0]
def gold_price(self, currency="USD"):
"""Gold quote plus 24k, 18k, 14k and 9k prices per ounce."""
data = self._get("/api/gold-price", {"currency": currency.upper()})
return data["results"][0]
def market_status(self):
"""Returns "OPEN" or "CLOSED"."""
return self._get("/api/market-status")["status"]
def _get(self, path, params=None):
request = requests.Request("GET", f"https://{HOST}{path}", params=params)
url = request.prepare().url
name = hashlib.md5(url.encode()).hexdigest()
cache_file = self.cache_dir / f"{name}.json"
if cache_file.is_file() and cache_file.stat().st_mtime > time.time() - self.cache_seconds:
return json.loads(cache_file.read_text())
try:
data = self._request(url)
except MetalSentinelError:
if cache_file.is_file():
return json.loads(cache_file.read_text())
raise
temp_file = self.cache_dir / f"{name}.{os.getpid()}.tmp"
temp_file.write_text(json.dumps(data))
os.replace(temp_file, cache_file)
return data
def _request(self, url):
headers = {
"X-RapidAPI-Key": self.api_key,
"X-RapidAPI-Host": HOST,
"Accept": "application/json",
}
try:
response = requests.get(url, headers=headers, timeout=10)
except requests.RequestException as exc:
raise MetalSentinelError(f"Request failed: {exc}") from exc
try:
data = response.json()
except ValueError:
data = None
if not isinstance(data, dict):
raise MetalSentinelError(f"Unexpected response (HTTP {response.status_code}).")
if "error" in data:
raise MetalSentinelError(f"API error: {data['error']}")
if "message" in data and response.status_code >= 400:
raise MetalSentinelError(
f"RapidAPI error (HTTP {response.status_code}): {data['message']}"
)
return data
How it works:
_get()builds the URL and looks for a cached copy first. A copy younger thancache_secondsis returned without calling the API.When the cache is old, it calls the API and saves the new response. It writes to a temporary file and renames it, so another worker never reads a half-written file.
If the API call fails (timeout, quota reached, network problem) and an older copy exists, it returns that copy, so the widget keeps showing the last known prices.
Errors from Metal Sentinel come back as
{"error": "..."}. Errors from RapidAPI itself, such as a wrong key or an exceeded quota, come back as{"message": "..."}with a 4xx status. The client turns both into aMetalSentinelError.
Try it from the command line. Save this as test_client.py:
import os
from metal_sentinel import MetalSentinelClient
client = MetalSentinelClient(os.environ["METAL_SENTINEL_KEY"])
gold = client.metal_quote("AU", "USD")
print(f"Gold: {gold['mid']} {gold['currency']} per ounce")
print("Market:", client.market_status())
python test_client.py
It prints the gold price and the market status:
Gold: 3884.7 USD per ounce
Market: OPEN
6. The widget
app.py loads four metals and hands them to a template:
import os
from datetime import datetime, timezone
from flask import Flask, render_template
from metal_sentinel import MetalSentinelClient, MetalSentinelError
app = Flask(__name__)
client = MetalSentinelClient(
api_key=os.environ["METAL_SENTINEL_KEY"],
cache_dir=os.path.join(app.root_path, "cache"),
cache_seconds=1800,
)
METALS = {"AU": "Gold", "AG": "Silver", "PT": "Platinum", "PD": "Palladium"}
def load_rows(currency="USD"):
rows = []
for symbol, name in METALS.items():
try:
quote = client.metal_quote(symbol, currency)
except MetalSentinelError as exc:
app.logger.warning("Metal widget: %s", exc)
continue
rows.append({"name": name, **quote})
return rows
@app.route("/widget")
def widget():
currency = "USD"
rows = load_rows(currency)
updated = None
if rows:
updated = datetime.fromtimestamp(rows[0]["timestamp"], tz=timezone.utc)
return render_template("widget.html", rows=rows, currency=currency, updated=updated)
templates/widget.html prints a small HTML card:
<div class="metal-widget">
<h3>Metal prices ({{ currency }}/oz)</h3>
{% if not rows %}
<p>Prices are not available right now.</p>
{% else %}
<table>
{% for row in rows %}
{% set up = row.change >= 0 %}
<tr>
<td>{{ row.name }}</td>
<td class="price">{{ "{:,.2f}".format(row.mid) }}</td>
<td class="{{ 'up' if up else 'down' }}">
{{ '▲' if up else '▼' }}
{{ "{:.2f}".format(row.changePercentage | abs) }}%
</td>
</tr>
{% endfor %}
</table>
<small>Updated {{ updated.strftime('%b %d, %H:%M') }} UTC</small>
{% endif %}
</div>
<style>
.metal-widget { font-family: system-ui, sans-serif; max-width: 320px; padding: 16px; border: 1px solid #e5e7eb; border-radius: 12px; }
.metal-widget h3 { margin: 0 0 12px; font-size: 16px; }
.metal-widget table { width: 100%; border-collapse: collapse; }
.metal-widget td { padding: 6px 0; border-bottom: 1px solid #f3f4f6; }
.metal-widget .price { text-align: right; font-weight: 600; }
.metal-widget .up, .metal-widget .down { text-align: right; width: 80px; }
.metal-widget .up { color: #16a34a; }
.metal-widget .down { color: #dc2626; }
.metal-widget small { display: block; margin-top: 8px; color: #6b7280; }
</style>
Start the development server and open http://127.0.0.1:5000/widget:
flask --app app run
To show the widget on any HTML page of the same site, load it in an <iframe>:
<iframe src="/widget" width="340" height="230"></iframe>
To put it inside another Flask template, call load_rows() in that view, pass rows, currency and updated to the template and add this line where the card should appear:
{% include "widget.html" %}
Jinja escapes every value it prints, so nothing from the API reaches the page unescaped.
7. Protect the key and the cache
Keep the key in the environment variable. If you load it from a
.envfile, add.envandcache/to.gitignore.Flask only serves files from
static/. Keepcache/outside that folder and visitors cannot download it.flask runstarts a development server. On a live site, run the app with a WSGI server such as Gunicorn.
pip install gunicorn
gunicorn -w 4 app:app
This starts four worker processes. They all read the same cache files, so the request count does not grow with the number of workers.
8. Choose a cache time that fits your plan
Each metal costs one request per cache refresh, however many visitors you have:
Metals | Cache time | Requests per month | Fits plan |
|---|---|---|---|
4 | 30 min (1800 s) | about 5,760 | Free (7,500) |
2 | 15 min (900 s) | about 5,760 | Free (7,500) |
4 | 5 min (300 s) | about 34,560 | Pro (45,000) |
4 | 1 min (60 s) | about 172,800 | Ultra (200,000) |
Set cache_seconds in app.py to match. When you test, remember that each change to symbols or currency is a new request.
9. Ideas for next steps
For other currencies, change
currencyinwidget()toEURorGBP. The API converts the price for you.For jewelry prices,
client.gold_price("USD")["karat_prices"]returns 24k, 18k, 14k and 9k prices per ounce. The gold price API page shows the full response.For the price per gram, divide
midby 31.1035.client.market_status()can power a badge that tells visitors whether prices are live or from the last close.For charts,
/api/metal-historyreturns daily prices between two Unix timestamps, up to 30 per page. Plotbidorask, becausemidis0in history results.In Django or FastAPI, import
MetalSentinelClientin a view and build the same rows. The module has no Flask code in it.
The Endpoints page lists every endpoint with its parameters. If you get stuck, use the contact form.