REST API code samples

Currency API examples for 20 popular stacks

Use CurrencyBeacon from your backend, frontend, mobile app, or internal SDK wrapper. Start with the REST API, then add MCP only when an LLM client needs the same exchange-rate data.

20 snippets REST-first SDK-ready JSON MCP optional
Quickstart
Latest USD rates
curl "https://api.currencybeacon.com/v1/latest?api_key=YOUR_API_KEY&base=USD&symbols=EUR,GBP,CAD"

{
  "meta": { "code": 200 },
  "response": {
    "base": "USD",
    "rates": {
      "EUR": 0.9184,
      "GBP": 0.7842,
      "CAD": 1.3571
    }
  }
}

Authenticate with one key

Pass your API key as api_key on REST requests. Keep it server-side for production apps.

Use the v1 base URL

All examples use https://api.currencybeacon.com/v1 and return lightweight JSON.

Handle the response envelope

Check meta.code, then read exchange-rate data from the response object.

Core REST endpoints

Start with the workflow you need

Use these endpoint patterns directly or wrap them in your own internal SDK for product, billing, finance, or reporting systems.

GET

Latest rates

Fetch current rates by base currency and optional symbol filter.

/v1/latest
GET

Convert

Convert an amount from one currency to another using live or historical data.

/v1/convert
GET

Historical

Request rates for a specific date for reconciliation and audit workflows.

/v1/historical
GET

Timeseries

Build charts or analyze rate movement over a date range.

/v1/timeseries
Top language and framework examples

20 copy-ready snippets

These examples are plain HTTP on purpose. Use them directly, or turn them into your own SDK layer.

JavaScript
/v1/latest

Fetch live rates in the browser or server runtime

const params = new URLSearchParams({
  api_key: 'YOUR_API_KEY',
  base: 'USD',
  symbols: 'EUR,GBP,CAD'
});

const response = await fetch(`https://api.currencybeacon.com/v1/latest?${params}`);
const payload = await response.json();

console.log(payload.response.rates);
TypeScript
/v1/convert

Add a small typed wrapper around convert

type ConversionResponse = {
  response: {
    from: string;
    to: string;
    amount: number;
    value: number;
  };
};

const url = new URL('https://api.currencybeacon.com/v1/convert');
url.search = new URLSearchParams({
  api_key: process.env.CURRENCYBEACON_API_KEY ?? '',
  from: 'USD',
  to: 'EUR',
  amount: '1250'
}).toString();

const data = await fetch(url).then((res) => res.json() as Promise<ConversionResponse>);
console.log(data.response.value);
Node.js
/v1/timeseries

Build a timeseries data source

const params = new URLSearchParams({
  api_key: process.env.CURRENCYBEACON_API_KEY,
  base: 'USD',
  symbols: 'EUR,GBP',
  start_date: '2025-01-01',
  end_date: '2025-01-31'
});

const res = await fetch(`https://api.currencybeacon.com/v1/timeseries?${params}`);
const json = await res.json();

console.log(json.response.rates);
React
/v1/latest

Load rates into a component

import { useEffect, useState } from 'react';

export function ExchangeRates() {
  const [rates, setRates] = useState({});

  useEffect(() => {
    const params = new URLSearchParams({
      api_key: import.meta.env.VITE_CURRENCYBEACON_API_KEY,
      base: 'USD',
      symbols: 'EUR,GBP,CAD'
    });

    fetch(`https://api.currencybeacon.com/v1/latest?${params}`)
      .then((res) => res.json())
      .then((json) => setRates(json.response.rates));
  }, []);

  return <pre>{JSON.stringify(rates, null, 2)}</pre>;
}
Next.js
/v1/convert

Proxy conversion through a route handler

export async function GET() {
  const params = new URLSearchParams({
    api_key: process.env.CURRENCYBEACON_API_KEY!,
    from: 'USD',
    to: 'EUR',
    amount: '1250'
  });

  const res = await fetch(`https://api.currencybeacon.com/v1/convert?${params}`, {
    next: { revalidate: 300 }
  });

  return Response.json(await res.json());
}
Python
/v1/currencies

Use requests for supported currencies

import os
import requests

response = requests.get(
    "https://api.currencybeacon.com/v1/currencies",
    params={"api_key": os.environ["CURRENCYBEACON_API_KEY"]},
    timeout=10,
)

response.raise_for_status()
payload = response.json()

print(payload["response"])
Django
/v1/convert

Return conversion data from a view

import os
import requests
from django.http import JsonResponse

def convert_usd_to_eur(request):
    response = requests.get(
        "https://api.currencybeacon.com/v1/convert",
        params={
            "api_key": os.environ["CURRENCYBEACON_API_KEY"],
            "from": "USD",
            "to": "EUR",
            "amount": request.GET.get("amount", "100"),
        },
        timeout=10,
    )

    return JsonResponse(response.json())
PHP
/v1/historical

Request historical rates with cURL

$query = http_build_query([
    'api_key' => 'YOUR_API_KEY',
    'date' => '2024-03-15',
    'base' => 'USD',
    'symbols' => 'EUR,GBP,JPY',
]);

$ch = curl_init('https://api.currencybeacon.com/v1/historical?'.$query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$json = curl_exec($ch);
curl_close($ch);

$rates = json_decode($json, true);
print_r($rates['response']['rates']);
Laravel
/v1/latest

Use the HTTP client inside a controller

use Illuminate\Support\Facades\Http;

$response = Http::timeout(10)->get('https://api.currencybeacon.com/v1/latest', [
    'api_key' => config('services.currencybeacon.key'),
    'base' => 'USD',
    'symbols' => 'EUR,GBP,CAD',
]);

$rates = $response->throw()->json('response.rates');
Ruby
/v1/latest

Fetch latest rates with Net::HTTP

require "net/http"
require "json"

uri = URI("https://api.currencybeacon.com/v1/latest")
uri.query = URI.encode_www_form(
  api_key: ENV.fetch("CURRENCYBEACON_API_KEY"),
  base: "USD",
  symbols: "EUR,GBP,CAD"
)

payload = JSON.parse(Net::HTTP.get(uri))
puts payload.dig("response", "rates")
Rails
/v1/convert

Wrap conversion in a service object

class CurrencyConverter
  BASE_URL = "https://api.currencybeacon.com/v1/convert"

  def self.call(amount:, from:, to:)
    uri = URI(BASE_URL)
    uri.query = URI.encode_www_form(
      api_key: Rails.application.credentials.currencybeacon_api_key,
      amount: amount,
      from: from,
      to: to
    )

    JSON.parse(Net::HTTP.get(uri)).dig("response", "value")
  end
end
Go
/v1/latest

Decode latest rates into a struct

package main

import (
  "encoding/json"
  "fmt"
  "net/http"
  "net/url"
  "os"
)

func main() {
  params := url.Values{}
  params.Set("api_key", os.Getenv("CURRENCYBEACON_API_KEY"))
  params.Set("base", "USD")
  params.Set("symbols", "EUR,GBP,CAD")

  res, _ := http.Get("https://api.currencybeacon.com/v1/latest?" + params.Encode())
  defer res.Body.Close()

  var payload map[string]any
  json.NewDecoder(res.Body).Decode(&payload)
  fmt.Println(payload["response"])
}
Java
/v1/convert

Use the Java 11 HTTP client

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

var apiKey = System.getenv("CURRENCYBEACON_API_KEY");
var uri = URI.create(
    "https://api.currencybeacon.com/v1/convert?api_key=" + apiKey +
    "&from=USD&to=EUR&amount=1250"
);

var request = HttpRequest.newBuilder(uri).GET().build();
var response = HttpClient.newHttpClient()
    .send(request, HttpResponse.BodyHandlers.ofString());

System.out.println(response.body());
Spring Boot
/v1/latest

Call latest rates from a service

import org.springframework.web.client.RestClient;

public class CurrencyBeaconClient {
  private final RestClient restClient = RestClient.create("https://api.currencybeacon.com/v1");

  public String latestRates(String apiKey) {
    return restClient.get()
      .uri(uri -> uri.path("/latest")
        .queryParam("api_key", apiKey)
        .queryParam("base", "USD")
        .queryParam("symbols", "EUR,GBP,CAD")
        .build())
      .retrieve()
      .body(String.class);
  }
}
C#
/v1/convert

Use HttpClient for conversion

using System.Net.Http.Json;

var apiKey = Environment.GetEnvironmentVariable("CURRENCYBEACON_API_KEY");
var url = $"https://api.currencybeacon.com/v1/convert?api_key={apiKey}&from=USD&to=EUR&amount=1250";

using var client = new HttpClient();
var payload = await client.GetFromJsonAsync<Dictionary<string, object>>(url);

Console.WriteLine(payload?["response"]);
ASP.NET Core
/v1/latest

Expose a server-side rates endpoint

app.MapGet("/rates", async (IConfiguration config, HttpClient http) =>
{
    var apiKey = config["CurrencyBeacon:ApiKey"];
    var url = $"https://api.currencybeacon.com/v1/latest?api_key={apiKey}&base=USD&symbols=EUR,GBP,CAD";

    var json = await http.GetStringAsync(url);
    return Results.Content(json, "application/json");
});
Kotlin
/v1/convert

Fetch a conversion from a coroutine

val apiKey = System.getenv("CURRENCYBEACON_API_KEY")
val url = "https://api.currencybeacon.com/v1/convert" +
  "?api_key=$apiKey&from=USD&to=EUR&amount=1250"

val client = java.net.http.HttpClient.newHttpClient()
val request = java.net.http.HttpRequest.newBuilder()
  .uri(java.net.URI.create(url))
  .GET()
  .build()

val response = client.send(request, java.net.http.HttpResponse.BodyHandlers.ofString())
println(response.body())
Swift
/v1/latest

Call latest rates with URLSession

let apiKey = ProcessInfo.processInfo.environment["CURRENCYBEACON_API_KEY"]!
let url = URL(string:
  "https://api.currencybeacon.com/v1/latest?api_key=\(apiKey)&base=USD&symbols=EUR,GBP,CAD"
)!

let (data, _) = try await URLSession.shared.data(from: url)
let json = try JSONSerialization.jsonObject(with: data)

print(json)
Rust
/v1/latest

Use reqwest for latest rates

use reqwest::Client;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let api_key = std::env::var("CURRENCYBEACON_API_KEY").unwrap();
    let json = Client::new()
        .get("https://api.currencybeacon.com/v1/latest")
        .query(&[
            ("api_key", api_key.as_str()),
            ("base", "USD"),
            ("symbols", "EUR,GBP,CAD"),
        ])
        .send()
        .await?
        .text()
        .await?;

    println!("{json}");
    Ok(())
}
Dart / Flutter
/v1/convert

Load conversion data in a mobile app

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<double> convertUsdToEur(String apiKey, double amount) async {
  final uri = Uri.https('api.currencybeacon.com', '/v1/convert', {
    'api_key': apiKey,
    'from': 'USD',
    'to': 'EUR',
    'amount': amount.toString(),
  });

  final response = await http.get(uri);
  final payload = jsonDecode(response.body);
  return payload['response']['value'];
}
Production checklist

Before you ship

  • Store API keys in environment variables or server-side secrets.
  • Check meta.code and handle non-200 responses before reading response.
  • Cache latest rates where your product can tolerate it to reduce repeated calls.
  • Use symbols filters when you only need a few currencies.
Next step

Build against live CurrencyBeacon data

Create an API key, test the samples, then move to the full API documentation for every parameter and response shape.