Consuming RESTful resources in Angular with $http, ngResource, and Restangular

Introduction

Chances are if you write an Angular app then at some point you’re going to need to communicate with a RESTful web service. On a basic level you could use Angular’s built-in $http service to do this. There’s nothing wrong with that but there’s more manual work involved with it. Thankfully Angular also provides their ngResource module that helps reduce verbosity and makes this interaction a little cleaner.

The third option and the one I personally prefer is Restangular. Restangular in my opinion provides more features than ngResource and an even cleaner means of working with resources. Nonetheless, I’m going to demonstrate how to consume a basic RESTful resource using all three methods.

For these examples we’re going to be consuming a RESTful resource that is setup to the following specification.

  • GET /hammers Returns a collection of hammers
  • GET /hammers/:id Returns a specific hammer
  • POST /hammers Creates a new hammer
  • PUT /hammers Updates a specific hammer
  • DELETE /hammers/:id Deletes a specific hammer

Using $http

The $http is fundamentally simple but as you can it requires you to pass a URL every time you make a request. Read more about the $http service here.

Using ngResource

With ngResource, once you’ve retrieved objects they are wrapped with instance functions like $save and $remove which make it easy to perform subsequent operations on them without the need to keep passing a URL.

One downside to using ngResource is that don’t naturally return promises, which is why you have to chain the $promise object. Read more about ngResource here.

Using Restangular

Restangular follows a similar pattern as ngResource in that once objects are retrieved they are wrapped with instance functions. One of Restangular‘s strong points is that you never need to pass it an actual URL, you just specify the starting resource and from there you can scope it down to all, one, or even sub-resources.

Read more about Restangular here.