How to use restangular

Building a restfull application using angular.js is supposed to be easy… and I am sure it is. However the moment I tried… as an inexperienced javascript programmer with even less angular experience… I had a hard time. This example will try to show you how I did manage.

Note that the resulting application might not be super usefull, but surely it will help to get acquainted with some aspects of the angular and restangular.

What we need

To get up and running, we need 2 things:

  1. a rest interface,
  2. an angular page, and
  3. a connection between the two (= javascript).

and we need these in this order. So let us move on…

Build the rest interface

Building a restfull interface is not hard. For my example I will point to another tutorial. This tutorial explains very well how to build a rest application using Flask (with Python as language). The tutorial is very well written and I urge you to read it! From now on it is assumed that the application is taken as described in that tutorial up untill the “Securing a RESTful web service” part. To keep things simple, this aspect will be ignored for now.

Than we have to add one part to the code, and that is the serving of static pages (otherwise you might end up with a “Cross-Origin Request” error). We want to make things as easy as possible. Therefore we do the following:

  1. Add a folder called “static” to the app folder (creating the path: app/static/)
  2. Add an import to the views.py
    from flask import redirect
  1. Add a route to the views.py
    @app.errorhandler(404)
    def not_found(error):
        #app.logger.info('some error')
        return make_response(jsonify({'error': 'Not found'}), 404)

This way, all files stored in the app/static folder will be served as-is. Here we can put our html, javascript, and css files.

Build the angular page

Here we dive immediately to the code:

<!doctype html >
<html ng-app="tasks">
<head>
    <title>Restangular Test</title>
    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-resource.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/restangular/1.4.0/restangular.js"></script>
</head>
<body>
    <p>Tasks</p>

    <div ng-controller="mainCtrl">
    <table>
        <thead>
            <tr>
                <th>Title</th>
                <th>Description</th>
                <th>Link</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="task in tasks">
                <td></td>
                <td></td>
                <td><a href="">link</a></td>
            </tr>
        </tbody>
    </table>
    </div>

    <script src="app.js"></script>
</body>
</html>

In the angular app we first define the header and include the external javascript-files (angular.js, angular-resource.js, angular-route.js, underscore.js, and restangular.js). Secondly we define the body, with:

  • a defined controller (div named mainCtrl),
  • a table with three columns,
  • the angular code to show the reply from our rest service, and
  • we include our own javascript file (which we will be writing in the next section).

We place the html in the index.html file in the app/static folder.

Connecting the angular application with our rest backend

This will all be done clientside using javascript. Therefore we create the file app/static/app.js with the following content:

// Define the application
app = angular.module('tasks', ['restangular']);

// Configure the application
app.config(function(RestangularProvider) {
    RestangularProvider.setBaseUrl(
        'http://127.0.0.1:5000/todo/api/v1.0'); 
        // Note that we run everything on the localhost
});

// Define the controller
app.controller('mainCtrl', function($scope, Restangular) {
    Restangular.all('tasks').getList().then(function(result) {
        $scope.tasks = result;
    });
});

// Standardize data format (extract from meta-data where needed)
app.config(function(RestangularProvider) {
    // add a response intereceptor
    RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
      var extractedData;
      // .. to look for getList operations
      if (operation === "getList") {
        // .. and handle the data and meta data
        extractedData = data.tasks;
      } else {
        extractedData = data;
      }
      return extractedData;
    });
});

In this file we do the following:

  1. we define the application name and the dependency on restangular,
  2. we configure the application by setting the base-url such that restangular can take care of the url-constructions (define once, use everywhere),
  3. we define the controller functionality (which is called from the html controller (mainCtrl), and
  4. we ensure that we always get the data in the same format (as a list)

To be continued…