Setting Up A Currency Convertor With ExchangeRatesApi.io
Products and services are increasingly accessed and bought online. As we live in a global village, if we have an online shop, many of our visitors will quite likely be based on a different country than our own, and use a different currency than our own.
If we want to provide a great user experience for them, to increase the chances of them buying our product, and coming back to the site, there is something very simple we can do: Display the price of the shopping items in their own currency. To achieve that, we can convert the price of the item from a base currency (say, EUR) to the visitor’s currency (say, CNY) using the exchange rate between the two currencies at that specific time.
Currency exchange rates change constantly, on an hourly basis (and even faster). This means that we can’t have a pre-defined list of exchange rates stored in our application; these must be gathered in real-time. However, this is not a problem nowadays. Thanks to APIs providing currency exchange data, we can add a currency convertor to our online shops rather effortlessly.
In this article, we will introduce ExchangeRatesApi.io, a popular API solution providing data for current and historical exchange rates for 168 currencies.
What We Want To Achieve
Simply said, we want to do what Amazon is doing: Give the option to the user in our online shop to display the prices in a currency of their own choosing.
When visiting a product page in amazon.co.uk, we are presented the price in British pounds:
But we can also see the price in a different currency, if we wish to. In the country/region settings, there is the option to change the currency:
After clicking on "Change", we are presented a select input, containing several pre-defined currencies. From among them, I’ve chosen the Euro:
Finally, back on the product page, the price is displayed in euros:
Having access to exchange rate data via an API, we can implement this same functionality for our own online shops.
How Do We Do It
ExchangeRatesApi.io provides a REST API, offering the latest forex data for 168 currencies. It is always up-to-date, compiling the data from a broad base of commercial sources and banks around the world.
After signing up on their service (tip: they have a free tier), we will be assigned an API access key:
We grab our API access key, and append it to the endpoint:
https://api.exchangeratesapi.io/v1/latest
?access_key=YOUR_API_KEY
To visualize the response, copy/paste the endpoint in your browser:
As can be possibly appreciated in the image above, the data for all 168 currencies has been retrieved. To narrow down the results to just a few of them, we indicate the currency codes via param symbols
.
For instance, to retrieve data for the USD, British pound, Australian dollar, Japanese Yen and Chinese Yuan (compared against the Euro, which is the base currency by default), we execute this endpoint:
https://api.exchangeratesapi.io/v1/latest
?access_key=YOUR_API_KEY
&symbols=USD,GBP,AUD,JPY,CNY
The response is the following:
{
"success": true,
"timestamp": 1620904263,
"base": "EUR",
"date": "2021-05-13",
"rates": {
"USD": 1.207197,
"GBP": 0.860689,
"AUD": 1.568196,
"JPY": 132.334216,
"CNY": 7.793428
}
}
What Data Can We Retrieve
ExchangeRatesApi.io provides several REST endpoints, to fetch different sets of data. Depending on the subscribed plan, endpoints may or may not be available (their pricing page explains what features are covered by each tier).
The endpoints indicated below must be attached to https://api.exchangeratesapi.io/v1/
(eg: latest
becomes https://api.exchangeratesapi.io/v1/latest
), and added the access_key
param with your API access key.
Latest rates
The latest
endpoint returns exchange rate data in real-time for all available currencies or for a specific set.
Currency Conversion
The convert
endpoint enables to convert an amount, from any currency to any other one within the supported 168 currencies.
Historical Rates
This endpoint has the shape YYYY-MM-DD
(such as 2021-03-20
), corresponding to the date for which we want to retrieve historical exchange rate information.
Time-Series Data
The timeseries
endpoint returns the daily historical data for exchange rates between two specified dates, for a maximum timeframe of 365 days.
Fluctuation Data
The fluctuation
endpoint returns the fluctuation data between specified dates, for a maximum timeframe of 365 days.
Fetching Data From The API
In order to implement the currency convertor, we can use the convert
endpoint (for which we need be subscribed to the Basic tier):
https://api.exchangeratesapi.io/v1/convert
?access_key=YOUR_API_KEY
&from=GBP
&to=JPY
&amount=25
The response we will obtain looks like this:
{
"success": true,
"query": {
"from": "GBP",
"to": "JPY",
"amount": 25
},
"info": {
"timestamp": 1620904845,
"rate": 154.245331
},
"historical": "",
"date": "2021-05-14",
"result": 3856.079212
}
Because the data is exposed via a REST API, we can conveniently retrieve it for any application based on any stack, whether it runs on the client-side or server-side, without having to install any additional library.
Client-Side
The following JavaScript code connects to the API, and prints the converted amount and exchange rate in the console:
// Set endpoint and your access key
const access_key = 'YOUR_API_KEY';
const from = 'GPB';
const to = 'JPY';
const amount = 25;
const url = https://api.exchangeratesapi.io/v1/convert?access_key=${ access_key }&from=${ from }&to=${ to }&amount=${ amount }
;
// Get the most recent exchange rates via the "latest" endpoint:
fetch(url)
.then(response => response.json())
.then(data => {
// If our tier does not support the requested endpoint, we will get an error
if (data.error) {
console.log('Error:', data.error);
return;
}
// We got the data
console.log('Success:', data);
console.log('Converted amount: ' + data.result);
console.log('(Exchange rate: ' + data.info.rate + ')');
})
.catch((error) => {
console.error('Error:', error);
});
Server-Side
The following code demonstrates how to connect to the REST API, and print the converted result, within a PHP application.
The same procedure can be implemented for other languages:
- Define the endpoint URL, attach your API access key.
- Connect to the endpoint, retrieve its response in JSON format.
- Decode the JSON data into an object/array.
- Obtain the converted amount from under the
result
property.
// Set endpoint and your access key
$access_key = 'YOUR_API_KEY';
$from = 'GBP';
$to = 'JPY';
$amount = 25;
// Initialize CURL:
$ch = curl_init("https://api.exchangeratesapi.io/v1/convert?access_key=${access_key}&from=${from}&to=${to}&amount=${amount}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Get the JSON data:
$json = curl_exec($ch);
curl_close($ch);
// Decode JSON response:
$conversionResult = json_decode($json, true);
// Access the converted amount
echo $conversionResult['result'];
Conclusion
ExchangeRatesApi.io was born as an open-source project, with the intention to provide current and historical foreign exchange rates published by the European Central Bank, and written in Python.
If you’d like to incorporate currency conversion for your online shop, to emulate Amazon and provide a compelling user experience for your visitors, then you can download and install the open-source project.
And you can also make it much easier: If you’d like to have your currency convertor working in no time, for any programming language, accessing always up-to-date data which includes a wide array of commercial sources, and from a super-fast API with uptime of nearly 100% (99.9% in the last 12 months), then check out ExchangeRatesApi.io.