Tuesday June 1, 2021 By David Quintanilla
Setting Up A Currency Convertor With ExchangeRatesApi.io — Smashing Magazine

About The Writer

Leonardo Losoviz is a contract developer and author, with an ongoing quest to combine revolutionary paradigms (Serverless PHP, server-side elements, GraphQL) …
More about

Amazon permits guests to show costs in their very own forex. Due to ExchangeRatesApi.io, we will do the identical for our on-line retailers, offering a greater expertise to our clients. Let’s learn the way.

Services and products are more and more accessed and purchased on-line. As we stay in a worldwide village, if we’ve a web based store, a lot of our guests will fairly seemingly be primarily based on a unique nation than our personal, and use a unique forex than our personal.

If we wish to present an excellent consumer expertise for them, to extend the probabilities of them shopping for our product, and coming again to the positioning, there’s something quite simple we will do: Show the worth of the buying gadgets in their very own forex. To realize that, we will convert the worth of the merchandise from a base forex (say, EUR) to the customer’s forex (say, CNY) utilizing the change charge between the 2 currencies at that particular time.

Foreign money change charges change always, on an hourly foundation (and even sooner). Which means we will’t have a pre-defined checklist of change charges saved in our utility; these have to be gathered in real-time. Nevertheless, this isn’t an issue these days. Due to APIs offering forex change information, we will add a forex convertor to our on-line retailers quite effortlessly.

On this article, we’ll introduce ExchangeRatesApi.io, a preferred API resolution offering information for present and historic change charges for 168 currencies.

What We Need To Obtain

Merely stated, we wish to do what Amazon is doing: Give the choice to the consumer in our on-line store to show the costs in a forex of their very own selecting.

When visiting a product web page in amazon.co.uk, we’re introduced the worth in British kilos:

Product page in amazon.co.uk, with price shown in pounds
Product web page in amazon.co.uk, with worth proven in kilos. (Large preview)

However we will additionally see the worth in a unique forex, if we want to. Within the nation/area settings, there’s the choice to alter the forex:

Dropdown with region settings
Dropdown with area settings. (Large preview)

After clicking on “Change”, we’re introduced a choose enter, containing a number of pre-defined currencies. From amongst them, I’ve chosen the Euro:

Dropdown with region settings
Dropdown with area settings. (Large preview)

Lastly, again on the product web page, the worth is displayed in euros:

Product page in amazon.co.uk, with price shown in euros.
Product web page in amazon.co.uk, with worth proven in euros. (Large preview)

Accessing change charge information by way of an API, we will implement this similar performance for our personal on-line retailers.

How Do We Do It

ExchangeRatesApi.io gives a REST API, providing the most recent foreign exchange information for 168 currencies. It’s all the time up-to-date, compiling the information from a broad base of economic sources and banks all over the world.

After signing up on their service (tip: they’ve a free tier), we will likely be assigned an API entry key:

Dashboard in ExchangeRatesApi.io
Dashboard in ExchangeRatesApi.io. (Large preview)

We seize our API entry key, and append it to the endpoint:


To visualise the response, copy/paste the endpoint in your browser:

Viewing the response to the REST API on the browser
Viewing the response to the REST API on the browser. (Large preview)

As will be presumably appreciated within the picture above, the information for all 168 currencies has been retrieved. To slim down the outcomes to just some of them, we indicate the currency codes via param symbols.

As an illustration, to retrieve information for the USD, British pound, Australian greenback, Japanese Yen and Chinese language Yuan (in contrast towards the Euro, which is the bottom forex by default), we execute this endpoint:


The response is the next:

 "success": true,
 "timestamp": 1620904263,
 "base": "EUR",
 "date": "2021-05-13",
 "charges": {
   "USD": 1.207197,
   "GBP": 0.860689,
   "AUD": 1.568196,
   "JPY": 132.334216,
   "CNY": 7.793428

What Knowledge Can We Retrieve

ExchangeRatesApi.io gives a number of REST endpoints, to fetch completely different units of knowledge. Relying on the subscribed plan, endpoints could or might not be obtainable (their pricing page explains what options are lined by every tier).

The endpoints indicated under have to be connected to https://api.exchangeratesapi.io/v1/ (eg: newest turns into https://api.exchangeratesapi.io/v1/newest), and added the access_key param along with your API entry key.

Newest charges

The latest endpoint returns change charge information in real-time for all obtainable currencies or for a selected set.

Foreign money Conversion

The convert endpoint allows to transform an quantity, from any forex to another one inside the supported 168 currencies.

Historic Charges

This endpoint has the shape YYYY-MM-DD (reminiscent of 2021-03-20), comparable to the date for which we wish to retrieve historic change charge info.

Time-Sequence Knowledge

The timeseries endpoint returns the each day historic information for change charges between two specified dates, for a most timeframe of three hundred and sixty five days.

Fluctuation Knowledge

The fluctuation endpoint returns the fluctuation information between specified dates, for a most timeframe of three hundred and sixty five days.

Fetching Knowledge From The API

With a purpose to implement the forex convertor, we will use the convert endpoint (for which we’d like be subscribed to the Primary tier):


The response we’ll receive seems like this:

 "success": true,
 "question": {
   "from": "GBP",
   "to": "JPY",
   "quantity": 25
 "data": {
   "timestamp": 1620904845,
   "charge": 154.245331
 "historic": "",
 "date": "2021-05-14",
 "end result": 3856.079212

As a result of the information is uncovered by way of a REST API, we will conveniently retrieve it for any utility primarily based on any stack, whether or not it runs on the client-side or server-side, with out having to put in any further library.


The next JavaScript code connects to the API, and prints the transformed quantity and change charge within the console:

// Set endpoint and your entry key
const access_key = 'YOUR_API_KEY';
const from = 'GPB';
const to = 'JPY';
const quantity = 25;
const url = `https://api.exchangeratesapi.io/v1/convert?access_key=${ access_key }&from=${ from }&to=${ to }&quantity=${ quantity }`;

// Get the latest change charges by way of the "newest" endpoint:
 .then(response => response.json())
 .then(information => {
   // If our tier doesn't help the requested endpoint, we'll get an error
   if (information.error) {
     console.log('Error:', information.error);

   // We obtained the information
   console.log('Success:', information);
   console.log('Transformed quantity: ' + information.end result);
   console.log('(Change charge: ' + information.data.charge + ')');
 .catch((error) => {
   console.error('Error:', error);


The next code demonstrates how to hook up with the REST API, and print the transformed end result, within a PHP application.

The identical process will be carried out for different languages:

  • Outline the endpoint URL, connect your API entry key.
  • Hook up with the endpoint, retrieve its response in JSON format.
  • Decode the JSON information into an object/array.
  • Get hold of the transformed quantity from beneath the end result property.
// Set endpoint and your entry key
$access_key = 'YOUR_API_KEY';
$from = 'GBP';
$to = 'JPY';
$quantity = 25;

// Initialize CURL:
$ch = curl_init("https://api.exchangeratesapi.io/v1/convert?access_key=${access_key}&from=${from}&to=${to}&quantity=${quantity}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Get the JSON information:
$json = curl_exec($ch);

// Decode JSON response:
$conversionResult = json_decode($json, true);

// Entry the transformed quantity
echo $conversionResult['result'];


ExchangeRatesApi.io was born as an open-source project, with the intention to supply present and historic overseas change charges printed by the European Central Financial institution, and written in Python.

In the event you’d like to include forex conversion to your on-line store, to emulate Amazon and supply a compelling consumer expertise to your guests, then you possibly can obtain and set up the open-source challenge.

And it’s also possible to make it a lot simpler: In the event you’d prefer to have your forex convertor working very quickly, for any programming language, accessing all the time up-to-date information which incorporates a big selection of economic sources, and from a super-fast API with uptime of almost 100% (99.9% within the final 12 months), then take a look at ExchangeRatesApi.io.

Smashing Editorial
(vf, yk, il)

Source link