Accessing APIs

Tweet Like

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);

See the Pen %= penName %> by Intel IDZ (@intelidz) on CodePen

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);

See the Pen %= penName %> by Intel IDZ (@intelidz) on CodePen

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"); }
});

See the Pen %= penName %> by Intel IDZ (@intelidz) on CodePen

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); 
});

See the Pen %= penName %> by Intel IDZ (@intelidz) on CodePen

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); };

See the Pen %= penName %> by Intel IDZ (@intelidz) on CodePen

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>

See the Pen %= penName %> by Intel IDZ (@intelidz) on CodePen

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.

Related API Links

Get started with the Intel XDK


Download Now