PHP (CURL)
Accessing Real-time exchange rates: Find below an example for how to access the latest exchange rate data via PHP (CURL):
// set API Endpoint and access key (and any options of your choice)
$endpoint = 'live';
$access_key = 'YOUR_ACCESS_KEY';
// Initialize CURL:
$ch = curl_init('https://api.exchangerate.host/'.$endpoint.'?access_key='.$access_key.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Store the data:
$json = curl_exec($ch);
curl_close($ch);
// Decode JSON response:
$exchangeRates = json_decode($json, true);
// Access the exchange rate values, e.g. GBP:
echo $exchangeRates['quotes']['USDGBP'];Performing a Currency Conversion: Converting one currency to another in PHP (CURL) is as simple as:
// set API Endpoint, access key, required parameters
$endpoint = 'convert';
$access_key = 'YOUR_ACCESS_KEY';
$from = 'USD';
$to = 'EUR';
$amount = 10;
// initialize CURL:
$ch = curl_init('https://api.exchangerate.host/'.$endpoint.'?access_key='.$access_key.'&from='.$from.'&to='.$to.'&amount='.$amount.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// get the (still encoded) JSON data:
$json = curl_exec($ch);
curl_close($ch);
// Decode JSON response:
$conversionResult = json_decode($json, true);
// access the conversion result
echo $conversionResult['result'];JavaScript (jQuery.ajax)
Echangerates can be easily accessed by using jQuery to make an AJAX call. This method is widely used and highly recommended due to its ease of integration.
Accessing Real-time exchange rates: Find below an example of how to access the latest exchange rate data via jQuery.ajax:
// set endpoint and your access key
endpoint = 'live'
access_key = 'YOUR_ACCESS_KEY';
// get the most recent exchange rates via the "live" endpoint:
$.ajax({
url: 'https://api.exchangerate.host/' + endpoint + '?access_key=' + access_key,
dataType: 'jsonp',
success: function(json) {
// exchange rata data is stored in json.quotes
alert(json.quotes.USDGBP);
// source currency is stored in json.source
alert(json.source);
// timestamp can be accessed in json.timestamp
alert(json.timestamp);
}
});Performing a Currency Conversion: Converting one currency to another in jQuery.ajax is as simple as:
// set endpoint and your access key
endpoint = 'convert';
access_key = 'YOUR_ACCESS_KEY';
// define from currency, to currency, and amount
from = 'EUR';
to = 'GBP';
amount = '10';
// execute the conversion using the "convert" endpoint:
$.ajax({
url: 'https://api.exchangerate.host/' + endpoint + '?access_key=' + access_key +'&from=' + from + '&to=' + to + '&amount=' + amount,
dataType: 'jsonp',
success: function(json) {
// access the conversion result in json.result
alert(json.result);
}
});Java
Using a variety of Apache HTTP Components, it's relatively simple to query the API in Java. Based on the following integration methods for the API's live and convert endpoints, we will provide a general idea of how to access Exchangerate JSON data in Java.
Accessing Real-time exchange rates: Find below an example for how to access and display the latest exchange rate data using Java:
package org.json.poc;
// necessary components are imported
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
public class LiveResponseDemo{
// essential URL structure is built using constants
public static final String ACCESS_KEY = "YOUR_ACCESS_KEY";
public static final String BASE_URL = "http://api.exchangerate.host/";
public static final String ENDPOINT = "live";
// this object is used for executing requests to the (REST) API
static CloseableHttpClient httpClient = HttpClients.createDefault();
/**
*
* Notes:
*
* A JSON response of the form {"key":"value"} is considered a simple Java JSONObject.
* To get a simple value from the JSONObject, use: .get("key");
*
* A JSON response of the form {"key":{"key":"value"}} is considered a complex Java JSONObject.
* To get a complex value like another JSONObject, use: .getJSONObject("key")
*
* Values can also be JSONArray Objects. JSONArray objects are simple, consisting of multiple JSONObject Objects.
*
*
*/
// sendLiveRequest() function is created to request and retrieve the data
public static void sendLiveRequest(){
// The following line initializes the HttpGet Object with the URL in order to send a request
HttpGet get = new HttpGet(BASE_URL + ENDPOINT + "?access_key=" + ACCESS_KEY);
try {
CloseableHttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
// the following line converts the JSON Response to an equivalent Java Object
JSONObject exchangeRates = new JSONObject(EntityUtils.toString(entity));
System.out.println("Live Currency Exchange Rates");
// Parsed JSON Objects are accessed according to the JSON resonse's hierarchy, output strings are built
Date timeStampDate = new Date((long)(exchangeRates.getLong("timestamp")*1000));
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String formattedDate = dateFormat.format(timeStampDate);
System.out.println("1 " + exchangeRates.getString("source") + " in GBP : " + exchangeRates.getJSONObject("quotes").getDouble("USDGBP") + " (Date: " + formattedDate + ")");
System.out.println("\n");
response.close();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// sendLiveRequest() function is executed
public static void main(String[] args) throws IOException{
sendLiveRequest();
httpClient.close();
new BufferedReader(new InputStreamReader(System.in)).readLine();
}
}The Java Output will look like this:
Live Currency Exchange Rates
1 USD in GBP : 0.66046 (Date: 2015-05-02 21:26:15 PM)