16

Click here to load reader

Angularjs & REST

Embed Size (px)

DESCRIPTION

Overview on methods to consume RESTful resources with AngularJS.

Citation preview

Page 1: Angularjs & REST

ANGULARJS & RESTGabriele Mittica

www.gabrielemittica.com - @gabrielemittica

Corley srl - www.corley.it

AngularJsDay 2014

Page 2: Angularjs & REST

What is REST?

“Representational State Transfer enablesintermediate processing by constrainingmessages to be self-descriptive: interaction isstateless between requests, standard methods and media types are used to indicate semantics and exchange information, and responses explicitly indicate cacheability.”

Roy Fielding, 2000

Client-Server

Stateless

Cacheable

UniformInterface

Page 3: Angularjs & REST

What is REST?

REST helps us to make apps with a frontend layer that works

with a separated backend layer that serves RESTful resources

Frontend Backend

Page 4: Angularjs & REST

Usually we create applicationsthat drive the logic, manage the data and serve the html to the client.

But now we can create an app(for example with AngularJS and HTML5) that works with RESTfulresources (JSON or XML)REST

Page 5: Angularjs & REST

AngularJS & REST

There are several ways to work with RESTful resources with AngularJS.

The most used are:

• $http

• ngResource

• Restangular

Page 6: Angularjs & REST

$http

Main features:

• It’s a core Angular service

• is based on the deferred/promise APIs exposed by the $q service

• Useful methods $http.get(), $http.post() …

• Auto transforming requests and responses (XSFR, JSON)

• Cache support

• Interceptors for requests and responses

Page 7: Angularjs & REST

$http example//GET request

$http({method: 'GET', url: '/user/123'}).

success(function(data, status, headers, config) {

// this callback will be called asynchronously

// when the response is available

}).

error(function(data, status, headers, config) {

// called asynchronously if an error occurs

// or server returns response with an error status.

});

//header config

$module.run(function($http) {

$http.defaults.headers.common.Authentication = 'Basic YmVlcDpib29w'

});

Page 8: Angularjs & REST

ngResource

Main features:

• Uses $resource (facotry that works with $http) to interact with RESTful services

• You need to add the script• <script src="//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-

resource.js">

• And load it into app• angular.module('app', ['ngResource']);

• Its methods let to work directly with the RESTful resource

Page 9: Angularjs & REST

ngResource ($resource) example//define the resource

var User = $resource('/user/:userId', {userId:'@id'});

//GET and SAVE requests

var user = User.get({userId:123}, function() {

user.newsletterSubscription = true;

user.$save(); //save is a POST request

});

//define the resource adding subscribe method

var User = $resource('/user/:userId', {userId:'@id'},

{subscribe: {method:'POST', params:{newsletterSubscription:true}}}

);

//GET and SAVE requests

var user = User.get({userId:123}, function() {

user.$subscribe();

});

Page 10: Angularjs & REST

Restangular

Main features:

• It’s an Angular service to simplify the consume of RESTful API

• Lodash (or Underscore) dependency

• Get it from https://github.com/mgonto/restangular

• Add to your APP:• angular.module('your-app', ['restangular']);

• angular.module('your-app').controller('MainCtrl', function($scope, Restangular) { ... });

• You don’t need to remember URLs

• It supports nested RestFUL resources and all HTTP methods.

Page 11: Angularjs & REST

Restangular example//define a base path and extractor

Restangular.withConfig(function(RestangularConfigurer){

RestangularConfigurer.setBaseUrl("/api/v1/");

RestangularConfigurer.setResponseExtractor(function(response, op) {

return response.data;

});

});

//define the resource adding subscribe method

var baseUsers = Restangular.all('user');

baseUsers.getList().then(function (users) {

var firstUser = users[0];

firstUser.name = "Clark Kent";

firstUser.put();

});

{

"data": [

{

"id": 123,

"name": "Superman"

},

{

"id": 999,

"name": "Batman"

}

],

"status": {

"success": true,

"time": 201

}

}

Page 12: Angularjs & REST

Appendix A: the errors

HTTP has a lot of status code (4xx client errors, 5xx server errors)But what if my request is correct, but the result of my request is notcorrect (for example the users sends a wrong answer in a poll) ?

{

"data": [],

"status": {

"success": false,

"errorCode": 1001,

"errorString": "Wrong answer"

}

}

Page 13: Angularjs & REST

Appendix B: the authentication

HTTP supports authentication (basic, digest…). In our AngularJS app we can add our authentication manager, usingthe following process:

User signed inServer returnsa secret key

The client usesthe key to sign the requests

Page 14: Angularjs & REST

Appendix B: the authentication

To do that we can use CryptoJS to sign each request:

getSignedParams: function(path, request, myKey, mySecret) {

var params = {};

if(request == null) {

request = "";

}

else {

request = JSON.stringify(request);

}

params.apiKey = myKey;

params.signature = CryptoJS.HmacSHA1(path+request, mySecret).toString();

return params;

}

Page 15: Angularjs & REST

Appendix B: the authentication

There is a problem in this process:If somebody steals my credentials, he can use them for the whole session.

A solution is change the credentials in each request (usefulin a mobile app but complicated in a web app where the user works on different tabs).

Page 16: Angularjs & REST

CODE GRUSP ON

CLOUDCONF.ITTHANK YOU

http://corsi.corley.it