Build a Simple REST Application with AngularJS Pt 1 Node API with Strongloop

The Project

Welcome to the first part of a series where we are going to learn how to build a simple REST website using AngularJS, Node.js and MongoDB. When we are finished with the series, we will have a fully working website with a master-detail interface that uses the $http service to communicate with a RESTful API that we will create using LoopBack from StrongLoop.

The code is divided into two repositories – the API and the website that consumes the API.

Simple Rest API Simple Rest Website

Seeing is Believing aka TLDR

Building the API

LoopBack provides a really easy way to generate a REST API in less than a minute. A minute? Totally not kidding! LoopBack uses Yeoman to provide the robot army to do our bidding, so basically you type a command and then answer some questions and done. If you want to see what happens in between terminal commands, please check out the video above. Read on for the highlights.

First you need to install the StrongLoop API server which is an NPM command.

$ npm install -g strongloop

And then we need to generate our project. You will enter in the directory where you want to create the project and your project name, which in this case will be simple-rest-api.

$ slc loopback

Now that the project is generated, we will jump into the project directory.

$ cd simple-rest-api

We then set up our datasource and point it to an ItemsDB database. This is where we choose MongoDB as our datasource.

$ slc loopback:datasource ItemsDB

And now to define our model. This is where we choose the datasource, input the plural form of the model name, and define the properties of the model.

$ slc loopback:model Item

Because we are using MongoDB, we need to install the loopback-connector-mongodb package.

$ npm install loopback-connector-mongodb

And we are ready to roll!

$ slc run

You will then be able to go to http://localhost:3000/explorer to see the StrongLoop API Explorer; this is a great utility for exploring and interacting with your new API.

Consuming the API

Simple REST Website

We are going to get into how to build the AngularJS website on top of our new minted API in the next lesson, but I wanted to take the opportunity to show you how to consume the API via the $http service.

When working with remote services, I like to extract out the endpoint URI into a constant so that if I need to change it, I only have to do it in one place. We accomplish this by creating a constant service called ENDPOINT_URI and giving it a value of http://localhost:3000/api/

 angular.module('SimpleRESTWebsite', [])
  .constant('ENDPOINT_URI', 'http://localhost:3000/api/')
  .service('ItemsModel', function ($http, ENDPOINT_URI) {
    // Pending
  });

We will also define a model called ItemsModel and inject in the $http and ENDPOINT_URI service into it. Because RESTful APIs are driven by convention, it is handy to create a few helper functions to generate the URLs you will use to communicate with the API. Because we are working with items, we will initialize a path variable to items/.

From here we will use getUrl and getUrlForId to generate our base URL and an item specific URL, respectively.

  angular.module('SimpleRESTWebsite', [])
  .constant('ENDPOINT_URI', 'http://localhost:3000/api/')
  .service('ItemsModel', function ($http, ENDPOINT_URI) {
    var service = this,
    path = 'items/';

<pre><code>function getUrl() {
  return ENDPOINT_URI + path;
}

function getUrlForId(itemId) {
  return getUrl(path) + itemId;
}

// Pending
</code></pre>
});

The $http service was built with convenience methods modeled after the REST verbs. This is great because, if you understand REST, the methods below will be fairly self documenting.

$http.get();
$http.post();
$http.put();
$http.delete();

And so let us examine these methods in the context of the ItemsModel.

angular.module('SimpleRESTWebsite', [])
  .constant('ENDPOINT_URI', 'http://localhost:3000/api/')
  .service('ItemsModel', function ($http, ENDPOINT_URI) {
    var service = this,
    path = 'items/';

<pre><code>function getUrl() {
  return ENDPOINT_URI + path;
}

function getUrlForId(itemId) {
  return getUrl(path) + itemId;
}

service.all = function () {
  return $http.get(getUrl());
};

service.fetch = function (itemId) {
  return $http.get(getUrlForId(itemId));
};

service.create = function (item) {
  return $http.post(getUrl(), item);
};

service.update = function (itemId, item) {
  return $http.put(getUrlForId(itemId), item);
};

service.destroy = function (itemId) {
  return $http.delete(getUrlForId(itemId));
};
</code></pre>
});

And now we can fully interact with our Node.js API! We can…

  • Get all items by calling service.all
  • Get a single item by calling service.fetch
  • Create an item by calling service.create
  • Update an existing item by calling service.update
  • Delete an existing item by calling service.delete

Review

We conclude this lesson with a Node.js REST API generated by LoopBack and consumed by the ItemsModel in AngualrJS. Just a quick review of what we covered.

  • LoopBack is a Node.js framework that helps you quickly create REST APIs
  • To work with LoopBack you need to install the StrongLoop API server via npm install -g strongloop
  • You can configure your data source and data models with slc strongloop:datasource and slc strongloop:model
  • LoopBack comes with an awesome API explorer which you can see at http://localhost:3000/explorer
  • The $http service has RESTful convenience methods such as get, post, put, delete, etc.

And I will leave you with this bit of code as a lead-in to the next installment of this series where we will build out the AngularJS portion of the project.

angular.module('SimpleRESTWebsite', [])
  .controller('MainCtrl', function (ItemsModel) {
    var main = this;

<pre><code>function getItems() {
  ItemsModel.all()
    .then(function (result) {
      main.items = result.data;
    });
}
getItems();
</code></pre>
})

I really love working with JavaScript, and the momentum of having great tools like AngularJS and LoopBack is sometimes just astonishing. I really hope I have sufficiently shown you a path to building awesome things a bit faster and better. See you in the next lesson!

Resources

Be sure to checkout the StrongLoop documentation as I have barely touched the surface of what it can do.

Getting Starting with StrongLoop

And the AngularJS docs are basically on speed dial.

Documentation for $HTTP

Check out a free video series I did for egghead.io that covers a lot of these same topics. My videos aside, egghead.io is one of the absolute best resources for learning AngularJS.

AngularJS App from Scratch

Simple Rest API Simple Rest Website

Leave a Comment