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 are able to do the identical for our on-line outlets, offering a greater expertise to our clients. Let’s learn the way.

Services are more and more accessed and purchased on-line. As we dwell in a worldwide village, if we’ve a web-based store, lots of our guests will fairly probably be based mostly on a distinct nation than our personal, and use a distinct forex than our personal.

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

Foreign money trade charges change always, on an hourly foundation (and even sooner). Which means that we are able to’t have a pre-defined listing of trade charges saved in our software; these should be gathered in real-time. Nonetheless, this isn’t an issue these days. Due to APIs offering forex trade knowledge, we are able to add a forex convertor to our on-line outlets quite effortlessly.

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

What We Need To Obtain

Merely mentioned, 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 value in British kilos:

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

However we are able to additionally see the value in a distinct forex, if we want to. Within the nation/area settings, there’s the choice to vary 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 value is displayed in euros:

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

Accessing trade fee knowledge through an API, we are able to implement this identical performance for our personal on-line outlets.

How Do We Do It

ExchangeRatesApi.io offers a REST API, providing the most recent foreign exchange knowledge for 168 currencies. It’s at all times up-to-date, compiling the info 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 could be probably appreciated within the picture above, the info 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.

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 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 offers a number of REST endpoints, to fetch totally 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 should be connected 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 trade fee knowledge in real-time for all obtainable currencies or for a particular set.

Foreign money Conversion

The convert endpoint permits to transform an quantity, from any forex to every other one throughout the supported 168 currencies.

Historic Charges

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

Time-Sequence Knowledge

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

Fluctuation Knowledge

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

Fetching Knowledge From The API

To be able to implement the forex convertor, we are able to use the convert endpoint (for which we want be subscribed to the Fundamental tier):


The response we are going to receive appears like this:

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

As a result of the info is uncovered through a REST API, we are able to conveniently retrieve it for any software 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 trade 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 newest trade charges through the "newest" endpoint:
 .then(response => response.json())
 .then(knowledge => {
   // If our tier doesn't help the requested endpoint, we are going to get an error
   if (knowledge.error) {
     console.log('Error:', knowledge.error);

   // We received the info
   console.log('Success:', knowledge);
   console.log('Transformed quantity: ' + knowledge.outcome);
   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 outcome, within a PHP application.

The identical process could 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.
  • Acquire the transformed quantity from below the outcome 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 trade charges revealed by the European Central Financial institution, and written in Python.

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

And it’s also possible to make it a lot simpler: Should you’d prefer to have your forex convertor working very quickly, for any programming language, accessing at all times up-to-date knowledge which incorporates a wide selection of economic 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