How to Fetch Live Gold Prices with PHP, Node.js and Python (REST and WebSocket)
Working PHP, Node.js and Python examples that fetch gram, quarter and has gold prices from a gold price API as JSON, cache them, and follow them live over WebSocket.
Updated: November 27, 2026
Before you start: key, base URL and symbols
Every example uses Pixcharp's Harem Gold API. The base URL is https://api.pixcharp.com and authentication is the X-API-Key header; an Authorization: Bearer header works too. You create the key in the customer dashboard. The 7-day free trial needs no card and includes 10,000 requests and 1 WebSocket connection.
The key starts with pxa_live_ and belongs on your server only. The examples read it from the PIXCHARP_API_KEY environment variable; never put it in browser code, a mobile app bundle or a Git repository.
There are four endpoints: GET /v1/prices returns every price, GET /v1/prices/{symbol} one symbol, GET /v1/symbols the symbols on your account and GET /v1/status the health of the feed. Common symbols: HAS (has gold), GRAM_ALTIN, CEYREK_YENI (quarter), YARIM_YENI (half), TAM_YENI (full), ATA_YENI, AYAR22 (22 karat), ONS (ounce), USDTRY and EURTRY.
Getting gold prices as JSON over REST
The simplest route is a single HTTP request. GET /v1/prices returns every gold and currency price in one response. alis is the buy price and satis the sell price; asOfUtc is the time of the price. stale: true means the data is older than expected, so use it to avoid showing a late price as if it were current.
When you need one price, a call such as GET /v1/prices/GRAM_ALTIN returns only that symbol's row: symbol, alis, satis, asOfUtc and stale.
curl https://api.pixcharp.com/v1/prices \
-H "X-API-Key: $PIXCHARP_API_KEY"{
"version": "v1",
"asOfUtc": "2026-11-14T10:24:13Z",
"source": "harem",
"stale": false,
"data": [
{ "symbol": "HAS", "alis": 6127.46, "satis": 6155.99, "asOfUtc": "2026-11-14T10:24:13Z", "stale": false },
{ "symbol": "GRAM_ALTIN", "alis": 6106.12, "satis": 6202.35, "asOfUtc": "2026-11-14T10:24:13Z", "stale": false }
]
}Gram gold price in PHP
PHP needs no extra library; the cURL extension is enough. The function below makes the request, checks the HTTP status and decodes the response into an array. On an error it throws, so you never silently show an empty or old price.
On PHP sites, do not fetch the price from the API on every page view. Keeping the result in APCu, Redis or a file for 30 to 60 seconds makes pages faster and protects your quota. On WordPress, the WordPress guide has a ready-made plugin that does the same with a transient.
<?php
// Keep the key in an environment variable, not in code.
function pixcharp_get(string $path): array
{
$client = curl_init("https://api.pixcharp.com" . $path);
curl_setopt_array($client, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["X-API-Key: " . getenv("PIXCHARP_API_KEY")],
CURLOPT_TIMEOUT => 10,
]);
$body = curl_exec($client);
$status = curl_getinfo($client, CURLINFO_HTTP_CODE);
if ($body === false || $status !== 200) {
throw new RuntimeException("Pixcharp API HTTP " . $status);
}
return json_decode($body, true);
}
$gram = pixcharp_get("/v1/prices/GRAM_ALTIN");
echo $gram["symbol"], " ", $gram["alis"], " / ", $gram["satis"], " (", $gram["asOfUtc"], ")", PHP_EOL;Fetching and caching every price in Node.js
From Node.js 18, fetch is built in. The example below fetches every price in one request, puts the rows in a Map by symbol and caches them for 30 seconds. Product cards, the price table and the cart all read from the same cache, so however many visitors you get, the API sees at most one request every 30 seconds.
On JavaScript or TypeScript, the open-source harem-altin-api client (npm install harem-altin-api) handles REST and WebSocket for you.
// Node.js 18+
const API = "https://api.pixcharp.com";
let cache = { at: 0, bySymbol: new Map() };
// Fetches every price in one request and caches it for 30 seconds.
export async function getGoldPrices() {
if (Date.now() - cache.at < 30_000) return cache.bySymbol;
const response = await fetch(API + "/v1/prices", {
headers: { "X-API-Key": process.env.PIXCHARP_API_KEY },
});
if (!response.ok) throw new Error("HTTP " + response.status);
const body = await response.json();
cache = { at: Date.now(), bySymbol: new Map(body.data.map((row) => [row.symbol, row])) };
return cache.bySymbol;
}
const prices = await getGoldPrices();
const gram = prices.get("GRAM_ALTIN");
console.log(gram.alis, gram.satis, gram.stale ? "(stale)" : "");Quarter gold price in Python
In Python, a few lines with requests are enough. raise_for_status() raises when the API returns an error such as 401, 403 or 429. The X-RateLimit-Remaining response header shows what is left of the per-minute limit and X-Quota-Remaining what is left of the monthly quota; logging them shows you early when the quota will run out.
# Install: pip install requests
import os
import requests
response = requests.get(
"https://api.pixcharp.com/v1/prices/CEYREK_YENI",
headers={"X-API-Key": os.environ["PIXCHARP_API_KEY"]},
timeout=10,
)
response.raise_for_status()
ceyrek = response.json()
print(ceyrek["symbol"], ceyrek["alis"], ceyrek["satis"], ceyrek["asOfUtc"])
print("Monthly quota left:", response.headers.get("X-Quota-Remaining"))Live gold prices over WebSocket
To show prices second by second, connect to the WebSocket stream instead of polling: wss://api.pixcharp.com/v1/stream. You use the same key as REST. On connect you get every price in one snapshot message; after that, as prices change, you get at most one prices message a second with only the symbols that changed in that second. A subscribe message lets you pick just the symbols you need.
WebSocket is included in the Pro and Business plans and in the free trial; Starter is REST only. The server sends a ping every 30 seconds and needs no reply. If the key is revoked, the address leaves the IP whitelist or the monthly quota runs out, the server sends an error message and closes with code 1008. Reconnect with backoff after every close; once the quota is used up, wait for the 1st (UTC).
// Install: npm install ws
import WebSocket from "ws";
const prices = new Map();
let attempt = 0;
let stopped = false;
function connect() {
const ws = new WebSocket("wss://api.pixcharp.com/v1/stream", {
headers: { "X-API-Key": process.env.PIXCHARP_API_KEY },
});
ws.on("open", () => {
attempt = 0;
// Optional: only the symbols you need.
ws.send(JSON.stringify({ type: "subscribe", symbols: ["GRAM_ALTIN", "CEYREK_YENI", "HAS"] }));
});
ws.on("message", (raw) => {
const message = JSON.parse(raw.toString());
if (message.type === "snapshot" || message.type === "prices") {
for (const row of message.data) prices.set(row.symbol, row);
}
if (message.type === "error") {
console.error(message.code, message.message);
// With the quota used up, reconnecting is pointless until the 1st (UTC).
if (message.code === "monthly_quota_exceeded") stopped = true;
}
});
ws.on("error", (error) => console.error(error.message));
ws.on("close", () => {
if (stopped) return;
// Reconnect with backoff: 1 s, 2 s, 4 s ... at most 60 s.
setTimeout(connect, Math.min(60_000, 1_000 * 2 ** attempt++));
});
}
connect();# Install: pip install "websockets>=14"
import asyncio
import json
import os
import websockets
prices = {}
async def main():
# async for reconnects with backoff when the connection drops.
async for ws in websockets.connect(
"wss://api.pixcharp.com/v1/stream",
additional_headers={"X-API-Key": os.environ["PIXCHARP_API_KEY"]},
):
try:
await ws.send(json.dumps({"type": "subscribe", "symbols": ["GRAM_ALTIN", "HAS"]}))
async for raw in ws:
message = json.loads(raw)
if message["type"] in ("snapshot", "prices"):
for row in message["data"]:
prices[row["symbol"]] = row
print(row["symbol"], row["alis"], row["satis"])
except websockets.ConnectionClosed:
continue
asyncio.run(main())Do you need WebSocket in PHP?
Classic PHP requests are short-lived: the process ends once the page is rendered. That is why REST with a short cache is usually enough for PHP sites. Refreshing the price once a minute is about 45,000 requests a month and fits easily in the 200,000-request Starter plan.
If you need second-by-second prices, open the WebSocket connection in a separate long-running process (like the Node.js or Python example above) and write incoming prices to Redis or your database. Your PHP pages read prices from there, and one connection serves the whole site.
Quota, limits and errors
Every REST call uses 1 request of your monthly quota. On WebSocket, each snapshot and prices message counts as 1 request; ping, pong, error and subscribed messages are free, and seconds with no change cost nothing. While the market keeps moving, one always-open connection can use about 2.7 million requests a month: about 11 days on Pro and the whole month on Business.
Common errors: 401 api_key_required or invalid_api_key (the key is missing or invalid), 403 ip_not_allowed (the address is not whitelisted), 404 unknown_symbol (no such symbol), 429 rate_limit_exceeded or monthly_quota_exceeded (per-minute limit or monthly quota reached), 503 price_feed_empty (source data not ready yet).
If you use the IP whitelist, add your server's outbound IP in the dashboard. The detail of a 403 ip_not_allowed response shows the address the API saw; when in doubt, that is the one to add.
Frequently asked questions
What format does the gold price API return?
JSON. Every row has symbol, alis (buy), satis (sell), asOfUtc and stale fields. GET /v1/prices returns the rows in a data array and GET /v1/prices/{symbol} returns a single row.
Should I use REST or WebSocket?
For prices shown on page load or refreshed once a minute, REST with a short cache is enough. To update prices on screen every second, the WebSocket stream fits better; it is included in Pro, Business and the free trial.
Can I use the API key in the browser?
It is not recommended. Anyone can see a key in the browser and spend your quota. Keep the key on your server and pass prices on to your pages from there.