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 modern paradigms (Serverless PHP, server-side parts, GraphQL) …
More about

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

Services are more and more accessed and acquired on-line. As we reside in a world village, if we’ve got a web based store, lots of our guests will fairly possible be based mostly on a unique nation than our personal, and use a unique foreign money than our personal.

If we need to present a fantastic consumer expertise for them, to extend the possibilities of them shopping for our product, and coming again to the positioning, there’s something quite simple we will do: Show the value of the purchasing objects in their very own foreign money. To attain that, we will convert the value of the merchandise from a base foreign money (say, EUR) to the customer’s foreign money (say, CNY) utilizing the change fee between the 2 currencies at that particular time.

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

On this article, we are going to introduce ExchangeRatesApi.io, a well-liked API resolution offering knowledge for present and historic change charges for 168 currencies.

What We Need To Obtain

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

When visiting a product web page in amazon.co.uk, we’re introduced the value 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 value in a unique foreign money, if we want to. Within the nation/area settings, there may be the choice to alter the foreign money:

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 value 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 fee knowledge by way of an API, we will implement this similar performance for our personal on-line retailers.

How Do We Do It

ExchangeRatesApi.io offers a REST API, providing the most recent foreign exchange knowledge for 168 currencies. It’s all the time up-to-date, compiling the information from a broad base of business sources and banks around the globe.

After signing up on their service (tip: they’ve a free tier), we shall 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 might be presumably appreciated within the picture above, the information for all 168 currencies has been retrieved. To slender down the outcomes to only a few of them, we indicate the currency codes via param symbols.

As an example, to retrieve knowledge for the USD, British pound, Australian greenback, Japanese Yen and Chinese language Yuan (in contrast towards the Euro, which is the bottom foreign money 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 Information Can We Retrieve

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

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

Newest charges

The latest endpoint returns change fee knowledge in real-time for all out there currencies or for a particular set.

Forex Conversion

The convert endpoint permits to transform an quantity, from any foreign money to another one inside the supported 168 currencies.

Historic Charges

This endpoint has the shape YYYY-MM-DD (akin to 2021-03-20), equivalent to the date for which we need to retrieve historic change fee data.

Time-Sequence Information

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

Fluctuation Information

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

Fetching Information From The API

With the intention to implement the foreign money convertor, we will use the convert endpoint (for which we want be subscribed to the Primary tier):


The response we are going to get hold of seems to be like this:

 "success": true,
 "question": {
   "from": "GBP",
   "to": "JPY",
   "quantity": 25
 "data": {
   "timestamp": 1620904845,
   "fee": 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 based mostly on any stack, whether or not it runs on the client-side or server-side, with out having to put in any extra library.


The next JavaScript code connects to the API, and prints the transformed quantity and change fee 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(knowledge => {
   // If our tier doesn't assist the requested endpoint, we are going to get an error
   if (knowledge.error) {
     console.log('Error:', knowledge.error);

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


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

The identical process might be applied for different languages:

  • Outline the endpoint URL, connect your API entry key.
  • Connect with the endpoint, retrieve its response in JSON format.
  • Decode the JSON knowledge into an object/array.
  • Receive the transformed quantity from below 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 knowledge:
$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 offer present and historic overseas change charges revealed by the European Central Financial institution, and written in Python.

When you’d like to include foreign money conversion in your on-line store, to emulate Amazon and supply a compelling consumer expertise in your guests, then you possibly can obtain and set up the open-source venture.

And it’s also possible to make it a lot simpler: When you’d prefer to have your foreign money convertor working very quickly, for any programming language, accessing all the time up-to-date knowledge which incorporates a wide selection of business sources, and from a super-fast API with uptime of almost 100% (99.9% within the final 12 months), then try ExchangeRatesApi.io.

Smashing Editorial
(vf, yk, il)

Source link

Leave a Reply