Categories: JavaJavascriptUI

AngularJS – Consume RESTful APIs with ngResource or $http


 

The article presents concepts and code samples on how to consume RESTful APIs with help of AngularJS $resource or $http service. The server side code is written on top of Spring MVC framework. Please feel free to point out suggestions on this blog.Following are key techniques using which one could consumer RESTful APIs

  1. Use low-level $http service to retrieve data using GET method. The demo could be found on this page
  2. Use $resource service to retrieve data using GET or QUERY action method. The demo could be found on this page

 

RESTful APIs with Low-level $http Service

One could directly use low-level $http service to consumer RESTful APIs using “GET” method as displayed in the code below. Pay attention to Spring MVC code where @PathVariable is used to receive the request based on URL template.

AngularJS Controller Code

var helloApp = angular.module("helloApp", []);
helloApp.controller("HttpController", [ '$scope', '$http',
 function($scope, $http) {
  $http({
   method : 'GET',
   url : '/user/25'
  }).success(function(data, status, headers, config) {
   $scope.profiles = data;
  }).error(function(data, status, headers, config) {
   alert( "failure");
  });
} ])

SpringMVC Controller Code

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET) 
public  @ResponseBody String getUserProfileById( @PathVariable("id") long userId )   {  
 //
 // Code processing the input parameters
 // 
 String response = "[{\"id\":\""+ userId + "\",\"firstname\":\"Aiyana\",\"lastname\":\"Shukla\",\"address\":\"Hyderabad, India\",\"age\":\"8\",\"email\":\"aiyana123@gmail.com\"}]";
 return response;
}
RESTful APIs with Low-level $resource Service

One could use $resource service which is an abstraction over $http service and uses this service underneath. I prefer this approach as it helps me to achieve the same objective with neat code based on object-based abstraction.

Following code samples represents how to consume RESTful APIs using GET or QUERY method. You may want to pay attention to usage of @PathVariable on Spring MVC side to retrieve the data coming with RESTful request.

Consuming RESTful APIs with GET Method

The code samples below would represent how to consume RESTful APIs by invoking “GET” action method on a $resource object.

AngularJS View Code

Following code represents the view code to display the response that arrived with RESTful API call. Pay attention to the fact that JSON response is assigned to $scope.profile in the callback function. The code below represents the usage of profile JSON object to display the view.

<table class="table">
 <tr>
  <th>Id
  </th>
  <th>Name
  </th>
  <th>Address
  </th>
  <th>Age
  </th>

 </tr>
 <tr>
  <td>{{profile.id}}
  </td>
  <td>{{profile.firstname + " " + profile.lastname}}
  </td>
  <td>{{profile.address}}
  </td>
  <td>{{profile.age}}
  </td>     
 </tr>
</table>

AngularJS Controller Code

Pay attention to some of the following in the code below:

  • Inclusion of ‘ngResource’ module at the time of instantiating the helloApp
  • Injecting ‘$resource’ service in the controller with name “HttpController”. The name of the controller could be anything.
  • Creation of a resource object, User
  • Invocation of “get” method on User resource object.
  • The response is processed using callback method which assigns the “user”, JSON response object, to $scope.profile
var helloApp = angular.module("helloApp", [ 'ngResource' ]);
helloApp.controller("HttpController", [ '$scope', '$resource',
 function($scope, $resource) {
  //
  // GET Action Method
  //
  var User = $resource('/user/:userId', {userId:'@userId'});
  User.get( {userId:25}, function(user){
   $scope.profile = user;
  })   
 } ]);

Spring MVC Controller Code

Pay attention to usage of @PathVariable for processing the template based URL.

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET) 
public  @ResponseBody String getUserProfileById( @PathVariable("id") long userId )   {  
 //
 // Code processing the input parameters
 // 
 String response = "{\"id\":\""+ userId + "\",\"firstname\":\"Aiyana\",\"lastname\":\"Shukla\",\"address\":\"Hyderabad, India\",\"age\":\"8\",\"email\":\"aiyana123@gmail.com\"}";
 return response;
}

 

Consuming RESTful APIs with QUERY Method
The code below represents the usage of QUERY action method when invoked on $resource object.
AngularJS View Code
Following code represents the view code to display the response that arrived with RESTful API call. Pay attention to the fact that JSON response consisting of array of objects is assigned to $scope.profiles in the callback function. The code below represents the usage of ng-repeat directive to display each of the profile JSON object to display the view.
<table class="table">
 <tr>
  <th>Id
  </th>
  <th>Name
  </th>
  <th>Address
  </th>
  <th>Age
  </th>

 </tr>
 <tr ng-repeat="profile in profiles">
  <td>{{profile.id}}
  </td>
  <td>{{profile.firstname + " " + profile.lastname}}
  </td>
  <td>{{profile.address}}
  </td>
  <td>{{profile.age}}
  </td>     
 </tr>
</table>

AngularJS Controller Code

Pay attention to some of the following:

  • Usage of “query” action method on UserProfiles resource object
var helloApp = angular.module("helloApp", [ 'ngResource' ]);
helloApp.controller("HttpController", [ '$scope', '$resource',
 function($scope, $resource) {
  //
  // Query Action Method
  //
  var UserProfiles = $resource('/getAllProfiles');
  UserProfiles.query(function(profiles){
   $scope.profiles = profiles;     
  });  
 } ]);

Spring MVC Controller Code

Pay attention to the fact that an array of JSON object is returned.

 
@RequestMapping(value = "/getAllProfiles", method = RequestMethod.GET)
 public  @ResponseBody String getAllProfiles( ModelMap model ) {
  String jsonData = "[{\"firstname\":\"ajitesh\",\"lastname\":\"kumar\",\"address\":\"211/20-B,mgstreet\",\"city\":\"hyderabad\",\"phone\":\"999-888-6666\"},{\"firstname\":\"nidhi\",\"lastname\":\"rai\",\"address\":\"201,mgstreet\",\"city\":\"hyderabad\",\"phone\":\"999-876-5432\"}]";
  return jsonData;
 }

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. For latest updates and blogs, follow us on Twitter. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking. Check out my other blog, Revive-n-Thrive.com

View Comments

  • /getAllProfiles is a very SOAP way of creating a REST API. Ideally you just have GET /profiles and to get a specific profile you'd use /profiles/:id.

Recent Posts

Pricing Analytics in Banking: Strategies, Examples

Last updated: 15th May, 2024 Have you ever wondered how your bank decides what to…

6 days ago

How to Learn Effectively: A Holistic Approach

In this fast-changing world, the ability to learn effectively is more valuable than ever. Whether…

1 week ago

How to Choose Right Statistical Tests: Examples

Last updated: 13th May, 2024 Whether you are a researcher, data analyst, or data scientist,…

1 week ago

Data Lakehouses Fundamentals & Examples

Last updated: 12th May, 2024 Data lakehouses are a relatively new concept in the data…

1 week ago

Machine Learning Lifecycle: Data to Deployment Example

Last updated: 12th May 2024 In this blog, we get an overview of the machine…

1 week ago

Autoencoder vs Variational Autoencoder (VAE): Differences, Example

Last updated: 12th May, 2024 In the world of generative AI models, autoencoders (AE) and…

1 week ago