AngularJS Easy API

By

I recently worked on a small Angular project that required interaction with a REST API. I found myself creating a wrapper service to make HTTP requests, and setting up constants for all of my endpoints. This was a bit time consuming and bothersome, since I’ve done the exact the same thing many times before for other projects I have worked on.

I decided to create a simple module that uses JSON to create a dynamic and injectable API service. This provides a way to get your application communicating with your server a lot quicker. It also keeps your entire API in one place, improving your code’s integrity and readability.

The actual logic behind the code is very similar to the module I wrote for interacting with Swagger endpoints in Angular, so I am not going to go to far in depth with how it was constructed. Instead, I’ll just show high-level example of how it works.

To get up and running, the first step is to install angular-easy-api using Bower or directly from Github.

bower install angular-easy-api --save

Once installed, include the required libraries and the angular-easy-api module in your application.

<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-easy-api/angular-easy-api.min.js"></script>
angular.module('myApp', ['easyAPI']);

After angular-easy-api has been added to your project, we can start constructing our API. In order to do this we must configure the API using the easyAPIProvider. We pass our JSON representation of our API to the provider, which will then be constructed into an easyAPI Object. By using easyAPI in our controllers and services, we can easily trigger HTTP requests to all of our endpoints.

Below is JSON which represents a simple REST API with three different endpoints that can be passed to our provider:

{
   "host": "localhost",
   "protocol": "http",
   "endpoints": {
       "/login": {
           "namespace": "auth",
           "methods": {
               "authenticate": "POST"
           }
       },

       "/todos/{id}": {
           "namespace": "todo",
           "methods": {
               "updateTodo": "POST",
               "getTodo": "GET"
           }
       },

       "/todos/list": {
           "namespace": "todo",
           "methods": {
               "listTodos": "GET"
           }
       }
   }
}

Each property maps to a function which triggers an HTTP request to it’s associated endpoint, and returns a Promise:

easyAPI[namespace][operationId]([data], [config])

data is an optional key/value mapping that can be used to pass data to the server. config is also optional, and can be used to override any property on Angular’s $http service config Object.

Therefore, the JSON above will create an easyAPI with four separate methods:

  • authenticate - Triggers a POST request to “http://localhost/auth/login”
  • updateTodo - Triggers a POST request to “http://localhost/todo/todos/{id}”
  • getTodo - Triggers a GET request to “http://localhost/todo/todos/{id}”
  • list - Triggers a GET request to “http://localhost/todo/list”

More information about how to structure the JSON for your API can be found in the Easy API README.

Once we have finished constructing our API, we pass it to the easyAPIProvider:

angular
    .module('myApp')
    .config(function(easyAPIProvider) {
        var api = {
           "host": "localhost",
           "protocol": "http",
           "endpoints": {
               "/login": {
                   "namespace": "auth",
                   "methods": {
                       "authenticate": "POST"
                   }
               },

               "/todos/{id}": {
                   "namespace": "todo",
                   "methods": {
                       "updateTodo": "POST",
                       "getTodo": "GET"
                   }
               },

               "/todos/list": {
                   "namespace": "todo",
                   "methods": {
                       "listTodos": "GET"
                   }
               }
           }
       };

       easyAPIProvider.setJSON(api);
    });

Now that our easyAPI is all set up, we can inject it into our controllers and services to start interacting with our server.

angular
    .module('myApp', ['easyAPI'])
    .controller('todoCtrl', todoCtrl);

function todoCtrl($log, easyAPI) {
    var vm = this;
    vm.list = list;

    function list() {
        easyAPI.todo.listTodos()
            .then(function(response) {
                $log.info('Todos:', response.data);
                // Do something cool!
            }, function(error) {
                $log.error(error);
                // Handle error
            });
    }
}

And that’s all there is to it! I think Easy API is useful when working in smaller Angular applications, since it eliminates having to add repetitive boiler-plate code that is required for interacting with a server. For complex applications, take a look at AngularSwaggerific.

The entire source code for Easy API can be found on Github.