Tech Industry News

Web Development

Need help with your website?

I’m Owen, a web developer and WordPress designer. I absolutely love building websites and helping people grow their businesses. Whether you just need a landing page or a custom tailored eCommerce solution, I’m here to design for you.

Are you ready to make your project a reality?

 

Get In Touch

Setting Up A Currency Convertor With ExchangeRatesApi.io

by | Jun 1, 2021 | Web Development | 0 comments

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.

Read More

How David Ellison Built Skydance Into Hollywood’s Smart Bet

When the young Oracle heir entered the entertainment industry, no one expected much. Instead, he’s built the rarest of businesses — a thriving, all-audiences, independent studio.Read More

Boeing 737 Max 10 completes first flight – CNET

The latest and largest member of the 737 Max family takes to the air seven months after the FAA cleared the aircraft to fly again. Read More

Prime Day Chromebook deals: The best we’ve found so far, starting at $169 – CNET

Get your hands on a new Chromebook for school or work from Amazon, Best Buy, Walmart and more. Read More

Apple TV HD review (2021): Why is this still a $149 thing? – CNET

If you want an Apple TV streaming box that badly, just spend the extra $30 for the 4K version. Read More

iPhone SE 3: All the juiciest rumors on size, design, and more – CNET

Will Apple keep iPhone SE's retro design or give it the glow up that many people have been pleading for? Here's what the we're hearing. Read More

Best Prime Day Apple deals right now on Apple Watch, AirPods Pro, iPads and more – CNET

As Prime Day approaches, here are the best Apple deals currently available. Read More

Best cars under $40,000 – Roadshow

The price doesn't have to keep you out of a good car, truck or SUV. Here are our favorites. Read More

2022 Honda Civic tested, Ford Bronco starts production and more: Roadshow’s week in review – Roadshow

Here's a look back at the car world's top stories for the week ending June 19. Read More

9 great reads from CNET this week: Amazon, iPhone cases, car culture and more – CNET

Some thoughts on Amazon, its workers and the reviews you find on its site, plus going case-free with an iPhone, driving around Los Angeles in a supercar and other good stuff. Read More

Let Users Own the Tech Companies They Help Build

Startups typically either go public or get acquired. But a more sustainable, accountable option would be to give the user base a stake.Read More
%d bloggers like this: