Wednesday, January 14, 2015

Writing a Client to Use a RESTful API

Now that one has a RESTful API to test against, one can write a web simple SPA to use it.  To get started writing sample code, create a free JSFIDDLE account <http://jsfiddle.net>.

Pure JavaScript

First, one can write the app without the aid of any JavaScript libraries.
1
2
3
4
5
6
7
8
9
10
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var wineries = JSON.parse(xmlhttp.responseText);
        alert(wineries.key1.name);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

With jQuery

One can write the app with the popular jQuery <http://jquery.com> JavaScript library.

note: One has to select jQuery 2.1.0 (or greater) in the Frameworks & Extensions in JSFIDDLE.
1
2
3
4
5
    alert(data.key1.name);
}).
fail(function() {
});

With AngularJS

While there is a little bit more overhead, which will be useful later, one can use the popular AngularJS <https://angularjs.org> JavaScript library.

note: One has to select AngularJS 1.2.1 (or greater) in the Frameworks & Extensions in JSFIDDLE.

HTML
1
2
3
4
<div ng-app="myApp">
    <div ng-controller="myCntrl">
    </div>
</div>

JavaScript
1
2
3
4
5
6
7
8
9
var myApp = angular.module('myApp', []);
myApp.controller('myCntrl', ['$http', function($http) {
        success(function(data, status, headers, config) {
            alert(data.key1.name);
        }).
        error(function(data, status, headers, config) {
        });
}]);


No comments:

Post a Comment