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.
var xmlhttp = new XMLHttpRequest();
var url = "https://wineapp.firebaseio.com/wineries.json";
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.
$.get( "https://wineapp.firebaseio.com/wineries.json", function(data) {
    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
<div ng-app="myApp">
    <div ng-controller="myCntrl">
    </div>
</div>

JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('myCntrl', ['$http', function($http) {
    $http.get('https://wineapp.firebaseio.com/wineries.json').
        success(function(data, status, headers, config) {
            alert(data.key1.name);
        }).
        error(function(data, status, headers, config) {
        });
}]);


No comments:

Post a Comment