Live data
Gold Price API
Real-time gold spot prices in 1,000+ currencies.
This tutorial builds a small PHP 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. Along the way you get an API key, write a short client class and cache the responses so the widget stays within the free plan.
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 to control the markup, mix the prices into your own pages or do calculations with them. If your site runs on Python, the Python version of this tutorial builds the same widget with Flask.
You need PHP 8.0 or newer with the cURL extension, which most shared hosts have enabled. You don't need Composer or a framework.
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 PHP:
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": 1794247620,
"results": [
{
"symbol": "AU",
"currency": "USD",
"ask": 4105.2,
"mid": 4104.2,
"bid": 4103.2,
"high": 4135.1,
"low": 4053.4,
"change": 33.1,
"changePercentage": 0.81,
"unit": "OUNCE",
"timestamp": 1794247560,
"originalTime": "2026-11-09T13:05:56.203Z"
}
]
}
Notes on the response:
resultsis an array. 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/
├── config.php (your API key, outside the public folder if you can)
├── MetalSentinelClient.php (the small client library)
├── cache/ (must be writable by PHP)
└── public/
└── widget.php (the widget page)
If your host only gives you one public folder, put everything there and block direct access to config.php and cache/ (see step 7).
4. Store the key in config.php
<?php
return [
'rapidapi_key' => 'YOUR_RAPIDAPI_KEY',
'cache_dir' => __DIR__ . '/cache',
'cache_seconds' => 1800,
];
If your server lets you set environment variables, use getenv('METAL_SENTINEL_KEY') instead of typing the key into the file, and keep the key out of Git.
5. The client library
MetalSentinelClient.php 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.
<?php
class MetalSentinelClient
{
private const HOST = 'metal-sentinel.p.rapidapi.com';
public function __construct(
private string $apiKey,
private string $cacheDir,
private int $cacheSeconds = 1800,
) {
if (!is_dir($this->cacheDir)) {
mkdir($this->cacheDir, 0775, true);
}
}
/**
* Live spot quote for one metal, e.g. metalQuote('AU', 'USD').
*/
public function metalQuote(string $symbol, string $currency = 'USD'): array
{
$data = $this->get('/api/metal-quote', [
'symbol' => strtoupper($symbol),
'currency' => strtoupper($currency),
]);
if (empty($data['results'][0])) {
throw new RuntimeException("No quote returned for {$symbol}.");
}
return $data['results'][0];
}
/**
* Gold quote plus 24k, 18k, 14k and 9k prices per ounce.
*/
public function goldPrice(string $currency = 'USD'): array
{
$data = $this->get('/api/gold-price', ['currency' => strtoupper($currency)]);
return $data['results'][0];
}
/**
* Returns "OPEN" or "CLOSED".
*/
public function marketStatus(): string
{
return $this->get('/api/market-status')['status'];
}
private function get(string $path, array $query = []): array
{
$url = 'https://' . self::HOST . $path;
if ($query) {
$url .= '?' . http_build_query($query);
}
$cacheFile = $this->cacheDir . '/' . md5($url) . '.json';
if (is_file($cacheFile) && filemtime($cacheFile) > time() - $this->cacheSeconds) {
return json_decode(file_get_contents($cacheFile), true);
}
try {
$data = $this->request($url);
} catch (RuntimeException $e) {
if (is_file($cacheFile)) {
return json_decode(file_get_contents($cacheFile), true);
}
throw $e;
}
file_put_contents($cacheFile, json_encode($data), LOCK_EX);
return $data;
}
private function request(string $url): array
{
$curl = curl_init($url);
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => [
'X-RapidAPI-Key: ' . $this->apiKey,
'X-RapidAPI-Host: ' . self::HOST,
'Accept: application/json',
],
]);
$body = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
if ($body === false) {
throw new RuntimeException('Request failed: ' . $curlError);
}
$data = json_decode($body, true);
if (!is_array($data)) {
throw new RuntimeException("Unexpected response (HTTP {$status}).");
}
if (isset($data['error'])) {
throw new RuntimeException('API error: ' . $data['error']);
}
if (isset($data['message']) && $status >= 400) {
throw new RuntimeException("RapidAPI error (HTTP {$status}): " . $data['message']);
}
return $data;
}
}
How it works:
get()builds the URL and looks for a cached copy first. A copy younger thancacheSecondsis returned without calling the API.When the cache is old, it calls the API and saves the new response.
If the API call fails (timeout, quota reached, network problem) and an older copy exists, it returns that copy. The widget keeps showing the last known prices instead of an error.
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 aRuntimeException.
Try it from the command line:
<?php
// test.php
require __DIR__ . '/MetalSentinelClient.php';
$config = require __DIR__ . '/config.php';
$client = new MetalSentinelClient($config['rapidapi_key'], $config['cache_dir'], $config['cache_seconds']);
$gold = $client->metalQuote('AU', 'USD');
echo "Gold: {$gold['mid']} {$gold['currency']} per ounce\n";
echo 'Market: ' . $client->marketStatus() . "\n";
php test.php
6. The widget
public/widget.php loads four metals and prints a small HTML card. Include it in an existing page or load it in an <iframe>.
<?php
require __DIR__ . '/../MetalSentinelClient.php';
$config = require __DIR__ . '/../config.php';
$client = new MetalSentinelClient($config['rapidapi_key'], $config['cache_dir'], $config['cache_seconds']);
$currency = 'USD';
$metals = ['AU' => 'Gold', 'AG' => 'Silver', 'PT' => 'Platinum', 'PD' => 'Palladium'];
$rows = [];
foreach ($metals as $symbol => $name) {
try {
$rows[] = ['name' => $name] + $client->metalQuote($symbol, $currency);
} catch (RuntimeException $e) {
error_log('Metal widget: ' . $e->getMessage());
}
}
?>
<div class="metal-widget">
<h3>Metal prices (<?= htmlspecialchars($currency) ?>/oz)</h3>
<?php if (!$rows): ?>
<p>Prices are not available right now.</p>
<?php else: ?>
<table>
<?php foreach ($rows as $row): ?>
<?php $up = $row['change'] >= 0; ?>
<tr>
<td><?= htmlspecialchars($row['name']) ?></td>
<td class="price"><?= number_format($row['mid'], 2) ?></td>
<td class="<?= $up ? 'up' : 'down' ?>">
<?= $up ? '▲' : '▼' ?>
<?= number_format(abs($row['changePercentage']), 2) ?>%
</td>
</tr>
<?php endforeach; ?>
</table>
<small>Updated <?= gmdate('M j, H:i', $rows[0]['timestamp']) ?> UTC</small>
<?php 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>
To put it on another page of the same site:
<?php include __DIR__ . '/widget.php'; ?>
Or from any HTML page:
<iframe src="/widget.php" width="340" height="230" style="border:0"></iframe>
All output goes through htmlspecialchars() or number_format(), so nothing from the API is printed into the page unescaped.
7. Protect the key and the cache
If config.php and cache/ sit inside your public web folder, block them. On Apache, add a .htaccess file in cache/:
Require all denied
and this to the .htaccess next to config.php:
<Files "config.php">
Require all denied
</Files>
Normally the server runs config.php and sends nothing back, so the key stays hidden. The rule protects the key if PHP is ever misconfigured.
On Nginx, add a location block that denies those paths.
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 config.php 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
$currencytoEURorGBP. The API converts the price for you.For jewelry prices,
$client->goldPrice('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->marketStatus()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.
The Endpoints page lists every endpoint with its parameters. If you get stuck, use the contact form.