SlideShare a Scribd company logo
ANGULARJS & REST
Gabriele Mittica
www.gabrielemittica.com - @gabrielemittica
Corley srl - www.corley.it
AngularJsDay 2014
What is REST?
“Representational State Transfer enables
intermediate processing by constraining
messages to be self-descriptive: interaction is
stateless 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
Uniform
Interface
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 applications
that 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 RESTful
resources (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 not
correct (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, using
the following process:
User signed in
Server returns
a secret key
The client uses
the 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 (useful
in a mobile app but complicated in a web app where the
user works on different tabs).
CODE GRUSP ON
CLOUDCONF.IT
THANK YOU
http://corsi.corley.it

More Related Content

PDF
How to connect AngularJS to servers
PPT
Using RESTFUL APIs in ANGULARJS
PDF
REST in AngularJS
ODP
AngularJS and REST - #omrs15 tutorial
PPTX
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
PDF
RESTful Web Services with Spring MVC
PDF
Building RESTful applications using Spring MVC
PPTX
Designing REST services with Spring MVC
How to connect AngularJS to servers
Using RESTFUL APIs in ANGULARJS
REST in AngularJS
AngularJS and REST - #omrs15 tutorial
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
RESTful Web Services with Spring MVC
Building RESTful applications using Spring MVC
Designing REST services with Spring MVC

What's hot (20)

KEY
REST Easy - Building RESTful Services in Zend Framework
PPTX
REST API for your WP7 App
PDF
Ch. 11 deploying
PPT
TSSJS2010 Presenatation on: Performance Anti Patterns In Ajax Applications
PPT
Performance anti patterns in ajax applications
PDF
Dynamic content generation
PDF
The Evolution of Airbnb's Frontend
PDF
Intro to RESTFul API's with ColdBox MVC
PDF
AJAX - An introduction
PDF
Server rendering-talk
PDF
HTML5 - An introduction
PDF
Learn REST in 18 Slides
PDF
SpringMVC
PPTX
Building Your First App with MongoDB
PDF
Rest with Spring
PPTX
The JSON REST API for WordPress
PPTX
Introduction about-ajax-framework
PDF
REST to JavaScript for Better Client-side Development
PDF
Getting Started With Angular
PDF
Ch. x web performance
REST Easy - Building RESTful Services in Zend Framework
REST API for your WP7 App
Ch. 11 deploying
TSSJS2010 Presenatation on: Performance Anti Patterns In Ajax Applications
Performance anti patterns in ajax applications
Dynamic content generation
The Evolution of Airbnb's Frontend
Intro to RESTFul API's with ColdBox MVC
AJAX - An introduction
Server rendering-talk
HTML5 - An introduction
Learn REST in 18 Slides
SpringMVC
Building Your First App with MongoDB
Rest with Spring
The JSON REST API for WordPress
Introduction about-ajax-framework
REST to JavaScript for Better Client-side Development
Getting Started With Angular
Ch. x web performance
Ad

Viewers also liked (10)

PDF
Build REST API clients for AngularJS
PPTX
REST in short
PDF
AngularJS application architecture
PDF
Laravel Restful API and AngularJS
PPTX
IT MATCH: Vastgoedfinanciering voor zelfstandigen / freelancers in België
PDF
Angular 2 for Java Developers
PDF
ARM CoAP Tutorial
PPTX
REST API Design
PDF
Rest web services
PDF
CoAP, Copper, and Embedded Web Resources
Build REST API clients for AngularJS
REST in short
AngularJS application architecture
Laravel Restful API and AngularJS
IT MATCH: Vastgoedfinanciering voor zelfstandigen / freelancers in België
Angular 2 for Java Developers
ARM CoAP Tutorial
REST API Design
Rest web services
CoAP, Copper, and Embedded Web Resources
Ad

Similar to Angularjs & REST (20)

PDF
Laravel + Restangular Introduction
PPTX
The future of web development write once, run everywhere with angular.js and ...
PDF
The future of web development write once, run everywhere with angular js an...
PDF
Angular Data
PDF
FITC presents: Mobile & offline data synchronization in Angular JS
PDF
Mean stack training-course-content
PPTX
Angular js
PDF
Flask and Angular: An approach to build robust platforms
PDF
Resources and relationships at front-end
PPTX
Restful webservices
ODP
Consume RESTful APIs with $resource and Restangular
PDF
Advanced I/O in browser
PPTX
REST Easy with AngularJS - ng-grid CRUD Example
PPTX
Webinar: AngularJS and the WordPress REST API
PPTX
Webinar: AngularJS and the WordPress REST API
PDF
Creating Restful Web Services with restish
PPTX
Angular js 1.0-fundamentals
PPTX
React vs Angular: ups & downs (speaker Oleksandr Kovalov, Binary Studio)
PDF
Angular - Chapter 7 - HTTP Services
PPTX
Introduction to Angular JS
Laravel + Restangular Introduction
The future of web development write once, run everywhere with angular.js and ...
The future of web development write once, run everywhere with angular js an...
Angular Data
FITC presents: Mobile & offline data synchronization in Angular JS
Mean stack training-course-content
Angular js
Flask and Angular: An approach to build robust platforms
Resources and relationships at front-end
Restful webservices
Consume RESTful APIs with $resource and Restangular
Advanced I/O in browser
REST Easy with AngularJS - ng-grid CRUD Example
Webinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST API
Creating Restful Web Services with restish
Angular js 1.0-fundamentals
React vs Angular: ups & downs (speaker Oleksandr Kovalov, Binary Studio)
Angular - Chapter 7 - HTTP Services
Introduction to Angular JS

More from Corley S.r.l. (20)

PDF
Aws rekognition - riconoscimento facciale
PDF
AWSome day 2018 - scalability and cost optimization with container services
PDF
AWSome day 2018 - API serverless with aws
PDF
AWSome day 2018 - database in cloud
PDF
Trace your micro-services oriented application with Zipkin and OpenTracing
PDF
Apiconf - The perfect REST solution
PDF
Apiconf - Doc Driven Development
PDF
Authentication and authorization in res tful infrastructures
PDF
Flexibility and scalability of costs in serverless infrastructures
PDF
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application
PDF
React vs Angular2
PDF
A single language for backend and frontend from AngularJS to cloud with Clau...
PPTX
AngularJS: Service, factory & provider
PPTX
The advantage of developing with TypeScript
PDF
Angular coding: from project management to web and mobile deploy
PDF
Corley cloud angular in cloud
PDF
Measure your app internals with InfluxDB and Symfony2
PDF
Read Twitter Stream and Tweet back pictures with Raspberry Pi & AWS Lambda
PDF
Deploy and Scale your PHP App with AWS ElasticBeanstalk and Docker- PHPTour L...
PDF
Middleware PHP - A simple micro-framework
Aws rekognition - riconoscimento facciale
AWSome day 2018 - scalability and cost optimization with container services
AWSome day 2018 - API serverless with aws
AWSome day 2018 - database in cloud
Trace your micro-services oriented application with Zipkin and OpenTracing
Apiconf - The perfect REST solution
Apiconf - Doc Driven Development
Authentication and authorization in res tful infrastructures
Flexibility and scalability of costs in serverless infrastructures
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application
React vs Angular2
A single language for backend and frontend from AngularJS to cloud with Clau...
AngularJS: Service, factory & provider
The advantage of developing with TypeScript
Angular coding: from project management to web and mobile deploy
Corley cloud angular in cloud
Measure your app internals with InfluxDB and Symfony2
Read Twitter Stream and Tweet back pictures with Raspberry Pi & AWS Lambda
Deploy and Scale your PHP App with AWS ElasticBeanstalk and Docker- PHPTour L...
Middleware PHP - A simple micro-framework

Recently uploaded (20)

PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
cuic standard and advanced reporting.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Electronic commerce courselecture one. Pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Machine learning based COVID-19 study performance prediction
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Empathic Computing: Creating Shared Understanding
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
MYSQL Presentation for SQL database connectivity
Unlocking AI with Model Context Protocol (MCP)
Spectral efficient network and resource selection model in 5G networks
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
20250228 LYD VKU AI Blended-Learning.pptx
cuic standard and advanced reporting.pdf
Approach and Philosophy of On baking technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
NewMind AI Monthly Chronicles - July 2025
Electronic commerce courselecture one. Pdf
Encapsulation_ Review paper, used for researhc scholars
Machine learning based COVID-19 study performance prediction
Mobile App Security Testing_ A Comprehensive Guide.pdf
Understanding_Digital_Forensics_Presentation.pptx

Angularjs & REST

  • 1. ANGULARJS & REST Gabriele Mittica www.gabrielemittica.com - @gabrielemittica Corley srl - www.corley.it AngularJsDay 2014
  • 2. What is REST? “Representational State Transfer enables intermediate processing by constraining messages to be self-descriptive: interaction is stateless 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 Uniform Interface
  • 3. 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
  • 4. Usually we create applications that 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 RESTful resources (JSON or XML)REST
  • 5. AngularJS & REST There are several ways to work with RESTful resources with AngularJS. The most used are: • $http • ngResource • Restangular
  • 6. $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
  • 7. $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' });
  • 8. 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
  • 9. 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(); });
  • 10. 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.
  • 11. 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 } }
  • 12. 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 not correct (for example the users sends a wrong answer in a poll) ? { "data": [], "status": { "success": false, "errorCode": 1001, "errorString": "Wrong answer" } }
  • 13. Appendix B: the authentication HTTP supports authentication (basic, digest…). In our AngularJS app we can add our authentication manager, using the following process: User signed in Server returns a secret key The client uses the key to sign the requests
  • 14. 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; }
  • 15. 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 (useful in a mobile app but complicated in a web app where the user works on different tabs).
  • 16. CODE GRUSP ON CLOUDCONF.IT THANK YOU http://corsi.corley.it