ADVISOR DETAILS

RECENT BLOG POSTS

JSON and XML

The previous blog talked about how to create an API query to enable us to programmatically access these APIs. Before we go into UI for the data, it is useful to understand the data that these APIs return.

Most APIs return data in one or both of the two formats – JSON and XML. They are textual data formats with well-defined ways to represent data which is both human and machine readable. The data formats themselves do not define the structure of the data. Thus, they are flexible and general enough to be used by any API service provider to represent their data.

JSON

JSON or Javascript Object Notation – is the most common data format for APIs today. It is derived from and uses the same notation as Javascript to represent data. Even though strongly linked to Javascript, parsers are also available for other modern languages as well. JSON is small, fast and easy to work with. Most modern browsers already have native functions for parsing JSON.  This has made it a popular format for data-interchange between server and client using APIs.

JSON is a collection of name-value pairs, where a value can be of the type number, string, boolean, array or another object. A simple example of JSON data is:

phonebook: [
  {
    name: ABC,
    phone: 111-111-1111
  },
  {
    name: XYZ,
    phone: 222-222-2222
  }
]

The JSON object phonebook is an array comprising of 2 objects. Each of these objects has two poperties – name and phone – associated with their corresponding values.

JSON.parse allows you to convert the JSON string to an object. Accessing any specific element would then be equivalent to traversing the JSON object. For example, in order to access the name of the first person in the phone book:

  var json = JSON.parse(jsonString);
  var nameOfFirstPerson = json.phonebook[0].name;

This ease of accessing and retreiving the data makes JSON appealing to be used programmatically, especially with Javascript.

XML

XML or Extensible Markup Language, as the name suggests, is a markup language which was designed to transport data between server and client. While the use of XML has come down recently, it is still a prevalant data format supported by several APIs, especially legacy ones.

XML looks very much like HTML, with tags and text content associated with each tags. You can define your own tags, allowing it to be used as a generalized format to represent API data. A simple example of XML data is:

<phonebook>
  <person>
    <name> ABC </name>
    <phone>111-111-1111</phone>
  </person>
  <person>
    <name> XYZ </name>
    <phone>222-222-2222</phone>
  </person>
<phonebook>

In the above data, “person”, “name”, “phone” are all XML tags. Since XML is similar to a DOM element, we can use the DOM parser that is available on most modern browsers to parse the XML string. This is done by:

function(xmlString) {
  if(window.DOMParser()) {
    var parser = new DOMParser();
    var xml = parser.parseFromString(xmlString, “text/xml”);
    return xml.documentElement;
  } }

This function returns the associated xml object. You can then query for child nodes and child elements using the same functions that work on any DOM element.

App Framework library makes this easy by abstracting out all the murky details into its $ functionality. $(xmlString) converts the string into an xml element. Accessing the rest of the elements is similar to traversing a DOM tree using functions such as find, childNodes, text etc..

var xml = $(xmlString);
var nameOfFirstPerson = xml.find("name").text();

More detailed documentation of the query selector functions can be found at App Framework library’s documentation site.

Read more >

Accessing APIs

The previous blog laid the groundwork for web APIs talking about why they are important, the basic structure and how to test. If you remember, we used the web browser to access and see the output in our previous examples. But using the web browser to access APIs is just a first step testing. Typically, we would like to access these APIs programmatically using Javascript. This blog talks briefly about different ways of accessing APIs and the components associated with the access.

Like I mentioned in the previous article, APIs are just like a webpage, but only return specific data either in XML or JSON format as defined by the API documentation. So, the way to access APIs is by HTTP requests. Javascript provides an object – XMLHttpRequest often also called XHR – for precisely this functionality.

Let’s consider the example of USA Today’s API. You can obtain the API key and replace YOUR_API_KEY with it to try out the same example. Using XMLHttpRequest, .

var url = “http://api.usatoday.com/open/articles/topnews/home?count=10&days=0&page=0&encoding=json&api_key=YOUR_API_KEY”;
var xhr = new XMLHttpRequest;
xhr.open("GET", url, true);
//Run this every time the connection state changes
xhr.onreadystatechange = function() { 
  if (xhr.readyState == 4) {  //Request is complete
    if(xhr.state == 200) {  //Response is ready
      alert("Request succeeded. Data:  "+xhr.responseText);
    }
  }
}
xhr.send(null);

This code is composed of two parts. The first part consisting of calls to open and send functions, is used to define and initiate the AJAX request. The GET in xhr.open indicates this is a GET request. A “POST” request is used to write to remote source.The other possible request types are “DELETE”, “PUT”, “HEAD” and “OPTIONS”.

The next part is where we wait for the request to complete. The “readyState” property of xhr indicates which state of connection the request is in. The values change from 0 to 4 signifying different stages of connection; 0 for request not yet initiated and 4 for request complete. The state property indicates the response from the server. The most common ones are 200 meaning All’s OK and 404 meaning page not found. Thus checking for readyState = 4 and state = 200, we verify that the request is complete and response is ready. This is our success handler function.

But what if the connection fails or the API url is wrong. Right now, we don’t have anything added to indicate that the request failed. In other words, we need an error handler. The above code can be easily modified to do this.

var url = “http://api.usatoday.com/open/articles/topnews/home?count=10&days=0&page=0&encoding=json&api_key=YOUR_API_KEY”;
var xhr = new XMLHttpRequest;
xhr.open("GET", url, true);
//Run this every time the connection state changes
xhr.onreadystatechange = function() { 
  if (xhr.readyState == 4) {  //Request is complete
    if(xhr.state == 200) {  //Response is ready
      alert("Request succeeded. Data:  "+xhr.responseText);
    } else { //Error handler
      alert(“Request failed with error code: ” + xhr.state); 
    }
  }
}
xhr.send(null);

This is quite a tedious process to make even a simple ajax request. Several Javascript libraries simplify this process by encapsulating all this into simple APIs. Let’s consider two libraries and how they handle this.

In jQuery, this is done using jQuery.ajax:

var url = “http://api.usatoday.com/open/articles/topnews/home?count=10&days=0&page=0&encoding=json&api_key=YOUR_API_KEY”;
$.ajax ({
 url: url,
 type: "GET",
 dataType: "json",

 success: function(data){ alert("Request succeeded. Data: " + data); }, 
 error: function(xhr) { alert("Request error"); }
});

jQuery.ajax takes as argument an object with key-value pairs, which can be used to configure the AJAX request. In the above example, we configure some of the basic properties for the AJAX request like the API url, method of request, data type that is returned by the request, success and error handler functions.

jQuery.getJSON is another simplified API particularly aimed at AJAX calls with JSON data. This is a shorthand for the above $.ajax API to get JSON data. The above code will be simplified to:

$.getJSON(url, function(data) {
 alert("Request succeeded. Data: " + data); 
});

Using Intel XDK, you can do the same using Appmobi.device.getRemoteData using:

var url = “http://api.usatoday.com/open/articles/topnews/home?count=10&days=0&page=0&encoding=json&api_key=YOUR_API_KEY”;
AppMobi.device.getRemoteData(url,
            "GET", "", "success", "failure");
function success(data) { alert ("Request succeeded. Data: " + data); }; 
function failure(data) { alert("error" + data); };

getRemoteData API takes 4 arguments, each associated with the API url, method of request, success and error handler function names. In order to use this API, you will also have to include – appmobi.js and xhr.js as:

<script type="text/javascript" charset="utf-8" src="http://localhost:58888/_appMobi/appmobi.js”></script>
<script type="text/javascript" charset="utf-8" src="http://localhost:58888/_appMobi/xhr.js”></script>

There are several other Javascript libraries which have similar APIs for making AJAX requests. The examples above are but a few to give some basic understanding. For other libraries, refer to the documentation of the corresponding libraries to understand more about how to use them.

This has hopefully got you started with using APIs in JavaScript. In the next few blogs, we will talk about most common data types and how to get useful data, cross-domain requests and other issues associated with AJAX requests.

Read more >