Click here to load reader
Upload
corley-srl
View
4.187
Download
0
Embed Size (px)
DESCRIPTION
Overview on methods to consume RESTful resources with AngularJS.
Citation preview
ANGULARJS & RESTGabriele Mittica
www.gabrielemittica.com - @gabrielemittica
Corley srl - www.corley.it
AngularJsDay 2014
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
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
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
AngularJS & REST
There are several ways to work with RESTful resources with AngularJS.
The most used are:
• $http
• ngResource
• Restangular
$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
$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'
});
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
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();
});
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.
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
}
}
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"
}
}
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
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;
}
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).
CODE GRUSP ON
CLOUDCONF.ITTHANK YOU
http://corsi.corley.it