JavaScript Examples
Complete JavaScript examples for integrating OpenFXRates using Fetch API, Node.js, and popular libraries.
Browser (Fetch API)
Example 1: Get Latest Rates
const apiKey = 'your-api-key-here';
const apiUrl = 'https://api.openfxrates.com';
async function getLatestRates(base, targets) {
try {
const params = new URLSearchParams({
base: base,
targets: targets
});
const response = await fetch(
`${apiUrl}/latest_rates?${params}`,
{
method: 'GET',
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json'
}
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(`Base: ${data.base}`);
console.log(`Date: ${data.date}`);
console.log('Rates:');
Object.entries(data.rates).forEach(([currency, rate]) => {
console.log(` ${currency}: ${rate.toFixed(4)}`);
});
return data;
} catch (error) {
console.error('Error fetching rates:', error);
}
}
// Usage
getLatestRates('USD', 'EUR,GBP,JPY');
Example 2: Convert Currency
async function convertCurrency(from, to, amount) {
const apiKey = 'your-api-key-here';
const apiUrl = 'https://api.openfxrates.com';
try {
const params = new URLSearchParams({
from: from,
to: to,
amount: amount
});
const response = await fetch(
`${apiUrl}/convert?${params}`,
{
headers: {
'X-API-Key': apiKey
}
}
);
const data = await response.json();
console.log(`Converting: ${amount} ${data.from}`);
console.log('Results:');
Object.entries(data.conversions).forEach(([currency, converted]) => {
console.log(` ${currency}: ${converted.toFixed(2)}`);
});
return data;
} catch (error) {
console.error('Conversion error:', error);
}
}
// Usage
convertCurrency('USD', 'EUR,GBP,JPY', 100);
Example 3: Get Historical Rates
async function getHistoricalRates(base, date, targets) {
const apiKey = 'your-api-key-here';
const apiUrl = 'https://api.openfxrates.com';
try {
const params = new URLSearchParams({
base: base,
date: date,
targets: targets
});
const response = await fetch(
`${apiUrl}/historical_rates?${params}`,
{
headers: {
'X-API-Key': apiKey
}
}
);
if (!response.ok) {
const error = await response.json();
throw new Error(error.message);
}
const data = await response.json();
console.log(`Historical rates for ${data.date}`);
console.log(`Base: ${data.base}`);
Object.entries(data.rates).forEach(([currency, rate]) => {
console.log(` ${currency}: ${rate.toFixed(4)}`);
});
return data;
} catch (error) {
console.error('Error fetching historical rates:', error);
}
}
// Usage - Get rates from January 15, 2024
getHistoricalRates('USD', '2024-01-15', 'EUR,GBP');
Example 4: List All Currencies
async function listCurrencies() {
const apiKey = 'your-api-key-here';
const apiUrl = 'https://api.openfxrates.com';
try {
const response = await fetch(
`${apiUrl}/currencies`,
{
headers: {
'X-API-Key': apiKey
}
}
);
const data = await response.json();
console.log(`Available currencies: ${data.currencies.length}\n`);
data.currencies.forEach(currency => {
const symbol = currency.symbol ? ` (${currency.symbol})` : '';
console.log(`${currency.code} - ${currency.name}${symbol}`);
});
return data.currencies;
} catch (error) {
console.error('Error listing currencies:', error);
}
}
// Usage
listCurrencies();
Node.js Examples
Setup: Installing Dependencies
# Using npm
npm install axios dotenv
# Or using yarn
yarn add axios dotenv
Example 5: Basic Node.js Request (Axios)
const axios = require('axios');
require('dotenv').config();
const apiKey = process.env.OPENFXRATES_API_KEY;
const baseUrl = 'https://api.openfxrates.com';
async function getLatestRates(base, targets) {
try {
const response = await axios.get(`${baseUrl}/latest_rates`, {
params: {
base: base,
targets: targets
},
headers: {
'X-API-Key': apiKey
}
});
return response.data;
} catch (error) {
console.error('Error:', error.response?.data || error.message);
throw error;
}
}
// Usage
getLatestRates('USD', 'EUR,GBP,JPY')
.then(data => {
console.log('Rates:', data.rates);
});
Example 6: API Client Class
const axios = require('axios');
class OpenFXRatesClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.openfxrates.com';
this.client = axios.create({
baseURL: this.baseUrl,
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json'
},
timeout: 30000
});
}
async getLatestRates(base, targets = null) {
try {
const response = await this.client.get('/latest_rates', {
params: { base, targets }
});
return response.data;
} catch (error) {
this.handleError(error);
}
}
async getHistoricalRates(base, date, targets = null) {
try {
const response = await this.client.get('/historical_rates', {
params: { base, date, targets }
});
return response.data;
} catch (error) {
this.handleError(error);
}
}
async convertCurrency(from, to, amount = 1) {
try {
const response = await this.client.get('/convert', {
params: { from, to, amount }
});
return response.data;
} catch (error) {
this.handleError(error);
}
}
async listCurrencies() {
try {
const response = await this.client.get('/currencies');
return response.data;
} catch (error) {
this.handleError(error);
}
}
handleError(error) {
if (error.response) {
const { status, data } = error.response;
console.error(`Error ${status}: ${data.message}`);
} else {
console.error('Request error:', error.message);
}
throw error;
}
}
module.exports = OpenFXRatesClient;
Example 7: Using the Client
const OpenFXRatesClient = require('./openFXRatesClient');
const client = new OpenFXRatesClient(process.env.OPENFXRATES_API_KEY);
async function demo() {
try {
// Get latest rates
const rates = await client.getLatestRates('USD', 'EUR,GBP,JPY');
console.log('Latest Rates:', rates);
// Convert currency
const conversion = await client.convertCurrency('USD', 'EUR,GBP', 100);
console.log('Conversion:', conversion);
// Get historical rates
const historical = await client.getHistoricalRates('USD', '2024-01-15', 'EUR');
console.log('Historical:', historical);
// List currencies
const currencies = await client.listCurrencies();
console.log(`Available: ${currencies.currencies.length} currencies`);
} catch (error) {
console.error('Demo error:', error.message);
}
}
demo();
Example 8: Error Handling and Retry Logic
const axios = require('axios');
class ResilientOpenFXRatesClient {
constructor(apiKey, maxRetries = 3) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.openfxrates.com';
this.maxRetries = maxRetries;
}
async request(endpoint, params = {}) {
let retries = 0;
while (retries < this.maxRetries) {
try {
const response = await axios.get(`${this.baseUrl}${endpoint}`, {
params,
headers: {
'X-API-Key': this.apiKey
},
timeout: 30000
});
return response.data;
} catch (error) {
// Handle rate limiting with backoff
if (error.response?.status === 429) {
const retryAfter = error.response.headers['retry-after'] || 60;
console.log(`Rate limited. Retrying in ${retryAfter}s...`);
await this.delay(retryAfter * 1000);
retries++;
continue;
}
// Handle authentication errors
if (error.response?.status === 401) {
throw new Error('Invalid API key');
}
// Handle bad requests
if (error.response?.status === 400) {
throw new Error(`Bad request: ${error.response.data.message}`);
}
// Retry on network errors
if (retries < this.maxRetries - 1 && !error.response) {
console.log(`Network error. Retrying (${retries + 1}/${this.maxRetries})...`);
await this.delay(1000 * (retries + 1));
retries++;
continue;
}
throw error;
}
}
throw new Error(`Failed after ${this.maxRetries} retries`);
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async getLatestRates(base, targets) {
return this.request('/latest_rates', { base, targets });
}
}
// Usage
const client = new ResilientOpenFXRatesClient(process.env.OPENFXRATES_API_KEY);
client.getLatestRates('USD', 'EUR,GBP')
.then(data => console.log(data))
.catch(error => console.error(error.message));
Example 9: Rate Caching
class CachedOpenFXRatesClient {
constructor(apiKey, cacheTTL = 3600000) { // 1 hour default
this.apiKey = apiKey;
this.baseUrl = 'https://api.openfxrates.com';
this.cache = new Map();
this.cacheTTL = cacheTTL;
}
getCacheKey(endpoint, params) {
return `${endpoint}:${JSON.stringify(params)}`;
}
async request(endpoint, params = {}) {
const cacheKey = this.getCacheKey(endpoint, params);
// Check cache
const cached = this.cache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < this.cacheTTL) {
console.log('Cache hit:', cacheKey);
return cached.data;
}
// Fetch from API
const response = await axios.get(`${this.baseUrl}${endpoint}`, {
params,
headers: { 'X-API-Key': this.apiKey }
});
// Cache result
this.cache.set(cacheKey, {
data: response.data,
timestamp: Date.now()
});
return response.data;
}
async getLatestRates(base, targets) {
return this.request('/latest_rates', { base, targets });
}
clearCache() {
this.cache.clear();
}
}
// Usage
const client = new CachedOpenFXRatesClient(process.env.OPENFXRATES_API_KEY);
// First call - fetches from API
client.getLatestRates('USD', 'EUR,GBP').then(data => console.log(data));
// Second call - returns from cache
client.getLatestRates('USD', 'EUR,GBP').then(data => console.log(data));
Best Practices
-
Store API Key in Environment Variable
require('dotenv').config();
const apiKey = process.env.OPENFXRATES_API_KEY; -
Use Try-Catch for Error Handling
try {
const data = await client.getLatestRates('USD', 'EUR');
} catch (error) {
console.error('Failed to fetch rates:', error.message);
} -
Implement Rate Limiting Handling
if (error.response?.status === 429) {
// Wait before retrying
} -
Cache Frequently Requested Data
// Cache rates for 1 hour -
Validate Parameters Before Sending
if (!base || !targets) {
throw new Error('Missing required parameters');
}
Next Steps
- PHP Examples → - PHP and cURL examples
- Python Examples → - Python examples
- API Reference → - Full endpoint documentation