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

About The Creator

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

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

Services and products are more and more accessed and acquired on-line. As we reside in a world village, if we’ve a web based store, a lot of our guests will fairly seemingly be primarily based on a distinct nation than our personal, and use a distinct foreign money than our personal.

If we need to present an ideal person expertise for them, to extend the possibilities of them shopping for our product, and coming again to the location, there’s something quite simple we will do: Show the worth of the purchasing gadgets in their very own foreign money. To realize that, we will convert the worth of the merchandise from a base foreign money (say, EUR) to the customer’s foreign money (say, CNY) utilizing the alternate fee between the 2 currencies at that particular time.

Foreign money alternate charges change consistently, on an hourly foundation (and even sooner). Which means we will’t have a pre-defined record of alternate charges saved in our utility; these should be gathered in real-time. Nonetheless, this isn’t an issue these days. Due to APIs offering foreign money alternate knowledge, we will add a foreign money convertor to our on-line retailers reasonably effortlessly.

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

What We Need To Obtain

Merely stated, we need to do what Amazon is doing: Give the choice to the person 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 offered 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 distinct foreign money, if we want to. Within the nation/area settings, there’s the choice to alter the foreign money:

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

After clicking on “Change”, we’re offered 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)

Getting access to alternate fee knowledge through an API, we will implement this identical performance for our personal on-line retailers.

How Do We Do It

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

After signing up on their service (tip: they’ve a free tier), we might 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 probably 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.

For 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 Knowledge Can We Retrieve

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

The endpoints indicated beneath should 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 along with your API entry key.

Newest charges

The latest endpoint returns alternate fee knowledge in real-time for all accessible currencies or for a particular set.

Foreign money Conversion

The convert endpoint allows to transform an quantity, from any foreign money to some other one throughout the supported 168 currencies.

Historic Charges

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

Time-Collection Knowledge

The timeseries endpoint returns the each day historic knowledge for alternate charges between two specified dates, for a most timeframe of 12 months.

Fluctuation Knowledge

The fluctuation endpoint returns the fluctuation knowledge between specified dates, for a most timeframe of 12 months.

Fetching Knowledge From The API

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


The response we are going to get hold of appears to be like 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 through 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 extra library.


The next JavaScript code connects to the API, and prints the transformed quantity and alternate 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 alternate charges through 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 acquired the information
   console.log('Success:', knowledge);
   console.log('Transformed quantity: ' + knowledge.end result);
   console.log('(Change 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.
  • Hook up 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 supply present and historic international alternate charges printed by the European Central Financial institution, and written in Python.

When you’d like to include foreign money conversion to your on-line store, to emulate Amazon and supply a compelling person expertise to your guests, then you’ll be able to obtain and set up the open-source mission.

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

Smashing Editorial
(vf, yk, il)

Source link

Leave a Reply