To get live gold prices in C#/.NET, send a GET to api.goldprice.dev/v1/spot/XAU-USD-SPOT with your API key in the X-API-Key header using HttpClient. Deserialize the JSON with System.Text.Json into a record with decimal fields, and cache the result for 60 seconds. The free tier covers 5,000 calls/month, no credit card. Tested July 2026 against .NET 8.
Get your goldprice.dev API key
Sign up for a free account at goldprice.dev/onboarding. After email confirmation, your dashboard shows a key starting with ga_live_. Set it as an environment variable:
export GOLDPRICE_API_KEY=ga_live_replace_with_your_key_hereThe free tier includes 5,000 calls/month and gold spot in 31 currencies. No credit card required.
Create the project
The .NET base class library covers everything needed: HttpClient for the request and System.Text.Json for deserialization. No third-party package is required, so scaffold a plain console app:
dotnet new console -o GoldpriceDemocd GoldpriceDemoWrite the goldprice client
Save this as GoldpriceClient.cs. SpotAsync() caches per symbol for 60 seconds in a ConcurrentDictionary, retries up to 3 times on 429 with exponential backoff, and deserializes prices into decimal fields via a custom JsonConverter, the API returns prices as JSON strings so precision survives the wire.
// GoldpriceClient.cs// curl-equivalent: https://api.goldprice.dev/v1/spot/XAU-USD-SPOTusing System.Collections.Concurrent;using System.Globalization;using System.Net.Http.Json;using System.Text.Json;using System.Text.Json.Serialization;namespace GoldpriceDemo;/// Converts the API's string-encoded price fields to decimal without/// the precision loss a double round-trip would introduce.public sealed class DecimalStringConverter : JsonConverter<decimal>{ public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => decimal.Parse(reader.GetString()!, CultureInfo.InvariantCulture); public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString());}public sealed record SpotResponse( [property: JsonPropertyName("symbol")] string Symbol, [property: JsonPropertyName("quote_currency")] string QuoteCurrency, [property: JsonPropertyName("price"), JsonConverter(typeof(DecimalStringConverter))] decimal Price, [property: JsonPropertyName("bid"), JsonConverter(typeof(DecimalStringConverter))] decimal? Bid, [property: JsonPropertyName("ask"), JsonConverter(typeof(DecimalStringConverter))] decimal? Ask, [property: JsonPropertyName("is_stale")] bool IsStale, [property: JsonPropertyName("computed_at")] string ComputedAt);public sealed class GoldpriceRateLimitedException : Exception{ public GoldpriceRateLimitedException() : base("goldprice: 429 rate limited") { }}public sealed class GoldpriceClient{ private const string ApiBase = "https://api.goldprice.dev"; private static readonly TimeSpan Ttl = TimeSpan.FromSeconds(60); private readonly HttpClient _http; private readonly ConcurrentDictionary<string, (SpotResponse Data, DateTimeOffset Expires)> _cache = new(); public GoldpriceClient(HttpClient http) { var apiKey = Environment.GetEnvironmentVariable("GOLDPRICE_API_KEY") ?? throw new InvalidOperationException("GOLDPRICE_API_KEY not set"); _http = http; _http.BaseAddress = new Uri(ApiBase); _http.Timeout = TimeSpan.FromSeconds(5); _http.DefaultRequestHeaders.Add("X-API-Key", apiKey); } /// Fetches the live spot price. Cached 60s per symbol, retries 3x on 429. public async Task<SpotResponse> SpotAsync(string symbol = "XAU-USD-SPOT", CancellationToken ct = default) { if (_cache.TryGetValue(symbol, out var cached) && cached.Expires > DateTimeOffset.UtcNow) { return cached.Data; } for (var attempt = 0; attempt < 3; attempt++) { using var response = await _http.GetAsync($"/v1/spot/{symbol}", ct); if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests) { await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)), ct); // 1s, 2s, 4s continue; } if (!response.IsSuccessStatusCode) { throw new HttpRequestException($"goldprice: unexpected status {(int)response.StatusCode}"); } var data = await response.Content.ReadFromJsonAsync<SpotResponse>(cancellationToken: ct) ?? throw new JsonException("goldprice: empty response body"); _cache[symbol] = (data, DateTimeOffset.UtcNow.Add(Ttl)); return data; } throw new GoldpriceRateLimitedException(); }}Run it
From the same shell where you exported GOLDPRICE_API_KEY, add a Program.cs that constructs the client and calls SpotAsync(). The first call hits the API; calls within 60 seconds return the cached record without a round-trip. A fresh process starts with an empty cache (in-process only), back it with a distributed cache such as Redis for cross-process sharing.
using GoldpriceDemo;using var http = new HttpClient();var client = new GoldpriceClient(http);var spot = await client.SpotAsync("XAU-USD-SPOT");Console.WriteLine($"{spot.Symbol}-{spot.QuoteCurrency}: {spot.Price} (computed {spot.ComputedAt})");// XAU-USD: 4012.75 (computed 2026-10-23T07:00:18.221118+00:00)Switch currency or metal
Symbols are METAL-CURRENCY-SPOT. Pass any of the 31 spot currencies to SpotAsync(). Each unique symbol caches independently in the ConcurrentDictionary, so a dashboard polling 5 symbols at 60-second intervals fires 5 uncached calls per minute and 0 cached.
// USD spot, defaultawait client.SpotAsync("XAU-USD-SPOT");await client.SpotAsync("XAU-INR-SPOT");await client.SpotAsync("XAU-EUR-SPOT");// Silver in USD, available on every planawait client.SpotAsync("XAG-USD-SPOT");Expected output
{ "symbol": "XAU", "quote_currency": "USD", "unit": "troy_ounce", "contract_type": "spot", "price": "4012.75", "is_stale": false, "computed_at": "2026-10-23T07:00:18.221118+00:00"}Stdout shows one line: symbol, quote currency, the price as a decimal, and the ISO 8601 ComputedAt timestamp. The SpotResponse record is what your downstream code consumes.
Common errors
| Code | What you see | Fix |
|---|---|---|
| 401 | goldprice: unexpected status 401 on the first call | API key missing or invalid. Confirm the variable is set: echo $GOLDPRICE_API_KEY. If empty, re-export from your dashboard. The GoldpriceClient constructor throws immediately when the env var is empty, so the failure surfaces at startup rather than mid-request. |
| 400 | goldprice: unexpected status 400, response body has "error": "invalid_symbol" | The symbol does not match BASE-QUOTE-CONTRACT (e.g. XAU-USD-SPOT). A bare metal code like XAU is rejected, always include the quote currency and contract token, and use SPOT or FUTURES, never FUT. |
| 429 | Three retries with backoff all return 429, then SpotAsync throws GoldpriceRateLimitedException | You hit the per-minute cap. The 60-second cache prevents this for steady polling; if a burst of distinct symbols arrives at once, stagger the calls. For sustained high-volume use, see /pricing for paid plans. |
| N/A | Deserialization throws JsonException or prices come through as 0 | The API sends prices as JSON strings (e.g. "4012.75"), not numbers. A plain decimal property without [JsonConverter(typeof(DecimalStringConverter))] fails to bind from a JSON string. Keep the converter attribute on every price field, or register it globally via JsonSerializerOptions.Converters. |
Going further
- Swap the
ConcurrentDictionaryforIMemoryCacheor a Redis-backedIDistributedCacheso an ASP.NET Core app shares one warm price across requests - Add a
BarsAsync()method for/v1/bars?symbol=XAU-USD-SPOT&interval=1d&from=...&to=...and feed the series into a backtest - Register GoldpriceClient with IHttpClientFactory and Polly for a policy-driven retry/circuit-breaker instead of the hand-rolled backoff loop
- Wire the client into a minimal API endpoint and serve internally for other services on the network
- Add OpenTelemetry instrumentation for cache hit rate, request latency, and 429-retry counts