currencylayer: Simple, Effective Currency Conversion

By  on  

Every developer that's maintained an eCommerce site will tell you that being responsible for properly handling currency will tell you it can be a very stressful task.  If you write buggy or insecure code, you're going to cost either your employer or the user money.  An added complication for developers can be currency conversion if the app caters to an international audience.  The last thing developers need is a complicated API, especially one that aids them in handling currency.  That's where currencylayer comes in:  a simple, comprehensive API for currency conversion for your web and native apps!

Quick Hits

Here are a few of the highlights of currencylayer's offering:

  • Trusted by Disney Pixar, FedEx, Lyft, and MetLife
  • Supports dozens of currencies
  • Supports bitcoin currency conversion
  • Provides HTTPS API usage
  • Currency value updates every 60 seconds
  • Clear documentation with numerous code samples (cURL, PHP, jQuery, etc.)
  • Very competitive pricing

Using currencylayer

currencylayer offers free signup with a generous request allotment for testing.  After you sign up you'll be given an API key to kick off development.  Armed with an API key and the documentation, it's time to use currencylayer's API endpoints to experiment with currencies!

Tips for All currencylayer Requests

  • All requests must be GET requests
  • The access_key parameter, which represents your API KEY, is required for all requests
  • You can add format=1 to any request to request currenclylayer format the JSON response (nice!)
  • You can add source={code} to change the source currency from USD to whichever language you'd like
  • You can add currency={currencylist} to specify which currencies you want information for
  • currencylayer provides extensive code samples in their documentation

Getting a Currency Listing

A good first step is using the currency listing endpoint to see which currencies are supported by currencylayer:

# The "list" endpoint provides a basic list of supported currencies
curl http://apilayer.net/api/list?access_key=MY_API_KEY&format=1
// Response:
{
   "success":true,
   "terms":"https:\/\/currencylayer.com\/terms",
   "privacy":"https:\/\/currencylayer.com\/privacy",
   "currencies":{
      "AED":"United Arab Emirates Dirham",
      "AFN":"Afghan Afghani",
      "ALL":"Albanian Lek",
      "AMD":"Armenian Dram",
      "ANG":"Netherlands Antillean Guilder",
      "AOA":"Angolan Kwanza",
      "ARS":"Argentine Peso",
      "AUD":"Australian Dollar",
      "BTC":"Bitcoin", // Yay bitcoin!
      // ...
      "USD":"United States Dollar",
      "UYU":"Uruguayan Peso",
      "UZS":"Uzbekistan Som",
      "VEF":"Venezuelan Bol\u00edvar Fuerte",
      "VND":"Vietnamese Dong"
   }
}

currencylayer supports an exhaustive list of currencies, opening up your international reach! Also note that you can add format=1 to your request URL to have

Getting Real-Time Rates

Real-time rate information is likely the most popular use of a currency conversion service like currencylayer, especially when you're dealing with a volatile currency like bitcoin.  In the case of eCommerce sites, once you get the user's location (via IP comparison or user preference), localized sites will display a localized price.

You can use the currencies key to get just the conversion you'd like

# Retrieve the value of USD compared to EUR (the Euro)
# If you don't provide a "currencies" key, all currencies will be returned
curl http://apilayer.net/api/live?format=1&currencies=EUR&access_key=MY_API_KEY
{
  "success":true,
  "terms":"https:\/\/currencylayer.com\/terms",
  "privacy":"https:\/\/currencylayer.com\/privacy",
  "timestamp":1494266647,
  "source":"USD",
  "quotes":{
    "USDEUR":0.914798
  }
}

Pulling currency rates "in bulk" is a smart way to limit API usage; currencylayer allows developers to grab multiple currency values at a time:

# Retrieve the value of USD compared to EUR (the Euro), GBP (Pound), BTC (Bitcoin)
curl http://apilayer.net/api/live?format=1&currencies=GBP,EUR,BTC&access_key=MY_API_KEY
{
  "success":true,
  "terms":"https:\/\/currencylayer.com\/terms",
  "privacy":"https:\/\/currencylayer.com\/privacy",
  "timestamp":1494266647,
  "source":"USD",
  "quotes":{
    "USDGBP":0.77271, // 1 USD is 0.77271 Pounds (GBP)
    "USDEUR":0.914798,
    "USDBTC":0.000628
  }
}

Unless you need to the moment accuracy, I'd recommend caching responses from currency layer to keep your system both speed and API usage efficient.  I love that currencylayer allows developers to grab information in bulk.

Getting Historical Currency Data

Retrieving historical data is also a nice feature from currencylayer, especially when you're working with volatile currencies.  This feature is great for building charts based on currency values.

# Get the value of BTC one year ago
curl http://apilayer.net/api/historical?date=2016-05-08¤cies=BTC&format=1&access_key=MY_API_KEY

# Get the value of BTC two years ago
curl http://apilayer.net/api/historical?date=2015-05-08¤cies=BTC&format=1&access_key=MY_API_KEY
// 2016
{
  "success":true,
  "terms":"https:\/\/currencylayer.com\/terms",
  "privacy":"https:\/\/currencylayer.com\/privacy",
  "historical":true,
  "date":"2016-05-08",
  "timestamp":1462751999,
  "source":"USD",
  "quotes":{
    "USDBTC":0.002177
  }
}

// 2015
{
  "success":true,
  "terms":"https:\/\/currencylayer.com\/terms",
  "privacy":"https:\/\/currencylayer.com\/privacy",
  "historical":true,
  "date":"2015-05-08",
  "timestamp":1431129599,
  "source":"USD",
  "quotes":{
    "USDBTC":0.004093
  }
}

The historical data endpoint accepts a single date argument and returns currency value for each supported currency.

Using JSONP

I'm a massive fan of JSONP; the number of times I've had to code a proxy to shim CORS has made me an annoyed, cynical developer.  currencylayer goes the extra mile to provide JSONP support:

// Get a conversion from USD to GBP for $20
$.ajax({
    url: 'http://apilayer.net/api/convert?access_key=MY_ACCESS_KEY&from=USD&to=GBP&amount=20,   
    dataType: 'jsonp',
    success: function(json) {
        // Update the pricing element with the GBP £ value
        document.querySelector('.price').html('£' + json.result);
    }
});

Thank you for providing JSONP support, currencylayer!

Time-Frame Queries

Time-frame queries are super useful for knowing currency value change with set start and end dates.  One example could be Another great example is refunding bitcoin transactions; if you base your bitcoin on USD, and bitcoin went up significantly since the origin transaction, you'll want to know the BTC value at the time of sale and adjust the BTC amount refunded to the customer.

# Customer wants a refund for a purchase made one month earlier
# In this case we need to figure out how much EUR has changed
curl http://apilayer.net/api/timeframe?start_date=2017-04-01&end_date=2017-05-01¤cies=EUR&format=1&access_key=MY_APK_KEY
{
  "success": true,
  "terms": "https://currencylayer.com/terms",
  "privacy": "https://currencylayer.com/privacy",
  "timeframe": true,
  "start_date": "2010-03-01",
  "end_date": "2010-04-01",
  "source": "USD",
  "quotes": {
    "2010-03-01": {
      "USDEUR": 0.738541
    },
    "2010-03-02": {
      "USDEUR": 0.736145
    },
    [...]
  }
}    

I also recommend checking out this Node.js resource which wraps currencylayer in a REST-like pattern, even allowing currency polling every x milliseconds!

Developing a system or app that accepts money, much less requires currency conversion, can be incredibly stressful; the last thing developers need is an overcomplicated API to do the currency work.  The currencylayer API is one of the easiest to use APIs I've ever worked with.  After evaluating a few other likewise currency conversion services, I can also add that currencylayer appears to be the most reasonably priced, which is a huge bonus.  If you develop systems that require currency conversion, or want to add localized pricing, give currencylayer a shot.  Simple, cost-effective, and developer-friendly!

Recent Features

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

Incredible Demos

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!