Create A Currency Converter in PHP, Python, Javascript and jQuery using Yahoo Currency API

Create A Currency Converter in PHP, Python, Javascript and jQuery using Yahoo Currency API

In this tutorial we’re going to develop a currency converter with the help of Yahoo Currency API. We are going to create this in different programming languages like php, python, javascript and jquery. All Currency formats follows ISO Standard (http://en.wikipedia.org/wiki/ISO_4217)

Using PHP + cURL

Please note that cURL must be enabled on your web server for this method to work, if cURL is not enabled we can use the second method file_get_contents instead of using cURL.

Code

<?php
function currencyConverter($currency_from,$currency_to,$currency_input){
    $yql_base_url = "http://query.yahooapis.com/v1/public/yql";
    $yql_query = 'select * from yahoo.finance.xchange where pair in ("'.$currency_from.$currency_to.'")';
    $yql_query_url = $yql_base_url . "?q=" . urlencode($yql_query);
    $yql_query_url .= "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
    $yql_session = curl_init($yql_query_url);
    curl_setopt($yql_session, CURLOPT_RETURNTRANSFER,true);
    $yqlexec = curl_exec($yql_session);
    $yql_json =  json_decode($yqlexec,true);
    $currency_output = (float) $currency_input*$yql_json['query']['results']['rate']['Rate'];

    return $currency_output;
}

 $currency_input = 2;
 //currency codes : http://en.wikipedia.org/wiki/ISO_4217
 $currency_from = "USD";
 $currency_to = "INR";
 $currency = currencyConverter($currency_from,$currency_to,$currency_input);

 echo $currency_input.' '.$currency_from.' = '.$currency.' '.$currency_to;

?>

Using PHP (file_get_contents)

If cURL is not enabled in the web server, we can use file_get_contents function to fetch our json response. Since our api call doesn’t require authentication we can alternatively use file_get_contents function.

Code

<?php
function currencyConverter($currency_from,$currency_to,$currency_input){
    $yql_base_url = "http://query.yahooapis.com/v1/public/yql";
    $yql_query = 'select * from yahoo.finance.xchange where pair in ("'.$currency_from.$currency_to.'")';
    $yql_query_url = $yql_base_url . "?q=" . urlencode($yql_query);
    $yql_query_url .= "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
    $yql_session = file_get_contents($yql_query_url);
    $yql_json =  json_decode($yql_session,true);
    $currency_output = (float) $currency_input*$yql_json['query']['results']['rate']['Rate'];

    return $currency_output;
}

 $currency_input = 2;
 //currency codes : http://en.wikipedia.org/wiki/ISO_4217
 $currency_from = "USD";
 $currency_to = "INR";
 $currency = currencyConverter($currency_from,$currency_to,$currency_input);

 echo $currency_input.' '.$currency_from.' = '.$currency.' '.$currency_to;

?>

Using Python

To acheive the same in python we use 2 python modules “urllib2” and “json”. “urllib2” module is used here to fetch the json response from Yahoo Currency API and “json” module is used to parse the json response.

Code

import urllib2
import json
def currencyConverter(currency_from,currency_to,currency_input):
    yql_base_url = "https://query.yahooapis.com/v1/public/yql"
    yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("'+currency_from+currency_to+'")'
    yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
    try:
        yql_response = urllib2.urlopen(yql_query_url)
        try:
            yql_json = json.loads(yql_response.read())
            currency_output = currency_input * float(yql_json['query']['results']['rate']['Rate'])
            return currency_output
        except (ValueError, KeyError, TypeError):
            return "JSON format error"
    
    except IOError, e:
        if hasattr(e, 'code'):
            return e.code
        elif hasattr(e, 'reason'):
            return e.reason

currency_input = 1
currency_from = "USD" # currency codes : http://en.wikipedia.org/wiki/ISO_4217
currency_to = "INR"
rate = currencyConverter(currency_from,currency_to,currency_input)
print rate

Using Javascript

We can use plain javascript to make ajax calls, but jQuery method is preferred because of browser compatibility.

Code

<script>
function httpGet(theUrl)
{
    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}
function currencyConverter(currency_from,currency_to,currency_input){
var yql_base_url = "https://query.yahooapis.com/v1/public/yql";
var yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("'+currency_from+currency_to+'")';
var yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
var http_response = httpGet(yql_query_url);
var http_response_json = JSON.parse(http_response);
//console.log(http_response);

return http_response_json.query.results.rate.Rate;
}
var currency_input = 1;
var currency_from = "USD"; // currency codes : http://en.wikipedia.org/wiki/ISO_4217
var currency_to = "INR";
var rate = currencyConverter(currency_from,currency_to,currency_input);
console.log(rate);
</script>

Using jQuery

Using jQuery is a good method because it is cross browser compatible. This method uses jquery get function. We can also use jquery ajax or getJSON functions.

Code

jQuery(document).ready(function($) {

var currency_input = 1;
var currency_from = "USD"; // currency codes : http://en.wikipedia.org/wiki/ISO_4217
var currency_to = "INR";

var yql_base_url = "https://query.yahooapis.com/v1/public/yql";
var yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("'+currency_from+currency_to+'")';
var yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";

var op_data =0;

$.get( yql_query_url, function( data ) {
op_data = data.query.results.rate.Rate;
console.log(op_data);
});

});

Download the code

Download From GitHub Download from Bitbucket