Introduction
In the fast-paced financial world, real-time currency conversion is a crucial tool. Whether you’re powering a pricing engine or an invoicing platform, having access to the latest exchange rates can mean the difference between profit and loss. In this tutorial, we’ll guide you on how to build a real-time currency conversion API using OpenExchangeAPI and Node.js.
Setting Up Your Environment
Before diving into the code, let’s set up your environment. You’ll need the following:
- Node.js and npm installed on your machine
- An API key from OpenExchangeAPI
- Express and Axios installed as dependencies in your project
You can install Express and Axios using npm like so:
npm install express axios
dotenv
Securing Your API Key
It’s crucial to keep your API key secure. We’ll use environment variables to avoid exposing the key in our code. Create a .env
file in the root of your project and add your OpenExchangeAPI key:
OPENEXCHANGE_API_KEY=your_api_key_here
Remember to add .env
to your .gitignore
file to prevent it from being committed to your version control system.
Building the API
Let’s build a simple Express server that uses Axios to fetch real-time exchange rates and perform currency conversion using OpenExchangeAPI.
1. Get Latest Exchange Rates
const express = require('express');
const axios = require('axios');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
const API_BASE = 'https://api.openexchangeapi.com/v1';
app.get('/latest', async (req, res) =>
{
const { base } = req.query;
try
{
const response = await axios.get(`${API_BASE}/latest`, {
params: base ? { base } : {},
headers: {
'Authorization': `Bearer ${process.env.OPENEXCHANGE_API_KEY}`
}
});
res.json(response.data);
}
catch (error)
{
if (error.response && error.response.status === 429)
{
return res.status(429).json({ error: 'Rate limit exceeded. Please try again later.' });
}
res.status(500).json({ error: error.toString() });
}
});
2. Convert Currency
app.get('/convert', async (req, res) =>
{
const { from, to, amount } = req.query;
if (!from || !to || !amount)
{
return res.status(400).json({ error: 'Missing required query parameters: from, to, amount' });
}
try
{
const response = await axios.get(`${API_BASE}/convert`, {
params: { from, to, amount },
headers: {
'Authorization': `Bearer ${process.env.OPENEXCHANGE_API_KEY}`
}
});
res.json(response.data);
}
catch (error)
{
if (error.response && error.response.status === 429)
{
return res.status(429).json({ error: 'Rate limit exceeded. Please try again later.' });
}
res.status(500).json({ error: error.toString() });
}
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Handling API Rate Limits
OpenExchangeAPI, like many APIs, enforces rate limits to ensure fair usage. If you exceed the provided limit, the API will respond with a 429
status code. The code above demonstrates how to handle this gracefully by returning a clear error message to the client.
Real-Time Currency Conversion in Action
Now that we have our API up and running, let’s see it in action. Open your favorite HTTP client and send a GET request to:
http://localhost:3000/latest?base=EUR
to get the latest rates with EUR as the base currency.http://localhost:3000/convert?from=USD&to=EUR&amount=100
to convert 100 USD to EUR.
Sample response for /convert
:
{
"from": "USD",
"to": "EUR",
"amount": 100,
"rate": 0.9174,
"result": 91.74
}
Conclusion
Voila! You’ve just built a backend service using Node.js and OpenExchangeAPI to perform real-time currency conversions. This API can be a powerful tool for many fin-tech applications, such as live pricing engines or invoicing platforms that require accurate and up-to-date exchange rates.
Remember to handle API rate limits gracefully and always secure your API keys. Happy coding!