Consuming a RESTful web service with AngularJS

duration 20 minutes

Explore how to access a simple RESTful web service and consume its resources with AngularJS in Open Liberty.

What you’ll learn

You will learn how to access a REST service and deserialize the returned JSON that contains a list of artists and their albums by using the high-level $resource service of AngularJS.

The REST service that provides the artists and albums resource was written for you in advance and responds with the following JSON:

[
    {
        "name": "foo",
        "albums": [
            {
                "title": "album_one",
                "artist": "foo",
                "ntracks": 12
            },
            {
                "title": "album_two",
                "artist": "foo",
                "ntracks": 15
            }
        ]
    },
    {
        "name": "bar",
        "albums": [
            {
                "title": "foo walks into a bar",
                "artist": "bar",
                "ntracks": 12
            }
        ]
    },
    {
        "name": "dj",
        "albums": [
        ]
    }
]

You will implement an AngularJS client that consumes this JSON and displays its contents at the following URL: http://localhost:9080

To learn more about REST services and how you can write them, see Creating a RESTful web service.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-rest-client-angularjs.git
cd guide-rest-client-angularjs

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project, which is what you will build.

Starting the service

Before you begin the implementation, start the provided REST service so that the artist JSON is available to you.

To start the REST service, run the Maven install and liberty:start-server goals from the start directory:

mvn clean install
mvn liberty:start-server

After you start the server, you can find your artist JSON at the following URL: http://localhost:9080/artists

Any local changes to your JavaScript and HTML are picked up automatically. After you start the Open Liberty server, you do not need to restart it.

Creating the AngularJS controller

Begin by registering your application module. Every application must contain at least one module, the application module, which will be bootstrapped to launch the application.

Create start/src/main/webapp/js/consume-rest.js and define the application module consumeRestApp:

var app = angular.module('consumeRestApp', []);

Your application will need some way of communicating with RESTful web services in order to retrieve their resources. In the case of this guide, your application will need to communicate with the artist service to retrieve the artist JSON. While there exists a variety of ways of doing this, you can use the fairly straightforward AngularJS $resource service.

To use the $resource service, register the ngResource module by appending it to your existing code in consume-rest.js:

var app = angular.module('consumeRestApp', ['ngResource']);

By registering another module, you are performing a dependency injection, exposing all functionalities of that module to your main application module.

Next, define the Artist AngularJS service by using the Factory recipe. The Factory recipe constructs a new service instance with the return value of a passed in function. In this case, the $resource module that you imported earlier is the passed in function. Target the artist JSON URL in the $resource() call.

app.factory("artists", function($resource) {
    return $resource("http://localhost:9080/artists");
});

Finally, create a controller and attach the artist property to its $scope parameter:

app.controller("ArtistsCtrl", function($scope, artists) {
    artists.query(function(data) {
        $scope.artists = data;
    }, function(err) {
        console.error("Error occured: ", err);
    });
});

The controller controls the flow of data in your application. Each controller is instantiated with its own isolated scope, accessible through the $scope parameter. All data that is bound to this parameter is available in the view to which the controller is attached.

You can now access the artists property from the template at the point in the Document Object Model (DOM) where the controller is registered.

Creating the AngularJS template

You can find the starting point of your application under start/src/main/webapp/index.html. This file is your template and will contain all elements and attributes specific to AngularJS.

Replace the contents of start/src/main/webapp/index.html with the following:

<!DOCTYPE html>
<html>
    <head>
        <script src='http://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.js'></script>
        <script src='http://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular-resource.js'></script>
        <script src='./js/consume-rest.js'></script>
    </head>
    <body ng-app='consumeRestApp'>
        <div ng-controller='ArtistsCtrl'>
            <div ng-repeat='artist in artists'>
                <p>{{ artist.name }} wrote {{ artist.albums.length }} albums:</p>
                <div ng-repeat='album in artist.albums'>
                    <p style='text-indent: 20px'>
                        Album titled <b>{{ album.title }}</b> by
                                     <b>{{ album.artist }}</b> contains
                                     <b>{{ album.ntracks }}</b> tracks
                    </p>
                </div>
            </div>
        </div>
    </body>
</html>

Before your application is bootstrapped, you must pull in two AngularJS libraries and import consume-rest.js:

<head>
    <script src='http://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.js'></script>
    <script src='http://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular-resource.js'></script>
    <script src='./js/consume-rest.js'></script>
</head>

The first import is the base AngularJS library. The second library is responsible for providing the APIs for the $resource service.

To bootstrap your application, attach the consumeRestApp application module to the body of your template:

<body ng-app='consumeRestApp'>
</body>

Next, attach the ArtistCtrl controller to the DOM to create a new child scope. This will make the artists property of the $scope object available to access at the point in the DOM where the controller is attached:

<body ng-app='consumeRestApp'>
    <div ng-controller='ArtistsCtrl'>
    </div>
</body>

Once the controller is attached, the artists property can be data-bounded to the template and accessed using the {{ artists }} expression. You can use the ng-repeat directive to iterate over the contents of the artists property:

<body ng-app='consumeRestApp'>
    <div ng-controller='ArtistsCtrl'>
        <div ng-repeat='artist in artists'>
            <p>{{ artist.name }} wrote {{ artist.albums.length }} albums:</p>
            <div ng-repeat='album in artist.albums'>
                <p style='text-indent: 20px'>
                    Album titled <b>{{ album.title }}</b> by
                                 <b>{{ album.artist }}</b> contains
                                 <b>{{ album.ntracks }}</b> tracks
                </p>
            </div>
        </div>
    </div>
</body>

After everything is set up, point your browser to the application root http://localhost:9080 to see the following output:

foo wrote 2 albums:
    Album titled album_one by foo contains 12 tracks
    Album tilted album_two by foo contains 15 tracks
bar wrote 1 albums:
    Album titled foo walks into a bar by bar contains 12 tracks
dj wrote 0 albums:

Testing the AngularJS client

No explicit code directly uses the consumed artist JSON, so you do not need to write any test cases for this guide.

Whenever you change your AngularJS implementation, the application root at http://localhost:9080 will reflect the changes automatically. You can visit the root to manually check whether the artist JSON was consumed correctly.

Although this guide did not teach you how to build logic, you will likely build logic when you develop your own applications, and testing will become a crucial part of your development lifecycle. If you need to write test cases, follow the official unit testing and end-to-end testing documentation on the AngularJS website: https://docs.angularjs.org/guide/unit-testing.

Great work! You’re done!

You have just accessed a simple RESTful web service and consumed its resources by using AngularJS in Open Liberty.

Contribute to this guide

Is something missing or broken? Raise an issue, or send us a pull request.