How to get live (spot) forex rate using API in Javascript?

< Back to Guides

JavaScript, often abbreviated JS, is a programming language that is one of the core technologies of the web. To get live forex rate using Javascript, we offer three sample code snippets using different method. Methods includes using Fetch, jQuery, or XHR.

For Node.js tutorial, please check out this link.

Instructions

  1. Get a free API key to use by signing up at forexrateapi.com and replace REPLACE_ME with your API key.
  2. Update base value to a currency or remove this query param.
  3. Update currencies value to a list of values or remove this query param.

For 2 and 3, you can find this documented at Offical Documentation

 

Using Fetch to fetch live forex rate in Javascript

var requestOptions = {
  method: 'GET',
  redirect: 'follow'
};

fetch("https://api.forexrateapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=EUR,JPY,CAD", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

 

Using jQuery to fetch live forex rate in Javascript

var settings = {
  "url": "https://api.forexrateapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=EUR,JPY,CAD",
  "method": "GET",
  "timeout": 0,
};

$.ajax(settings).done(function (response) {
  console.log(response);
});

 

Using XHR to fetch live forex rate in Javascript


var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
  if(this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "https://api.forexrateapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=EUR,JPY,CAD");

xhr.send();