How $resource simplifies RESTful API integration?

Loading

In AngularJS, making RESTful API calls with $http requires writing multiple methods for GET, POST, PUT, and DELETE operations. However, $resource (from ngResource module) provides a more structured, declarative, and simpler way to interact with RESTful APIs.


Why Use $resource Instead of $http?

Simplifies API Calls – No need to manually define HTTP methods.
Encapsulates API Endpoints – Treats API resources as objects.
Reduces Code Complexity – Less repetitive code compared to $http.
Automatic Data Binding – Returns promises and binds responses easily.


1. Setting Up $resource

Step 1: Include ngResource Module

Before using $resource, ensure the ngResource module is included in your project.

Include AngularJS and ngResource in HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-resource.min.js"></script>

Add ngResource Dependency in Your AngularJS App

var app = angular.module('myApp', ['ngResource']);

2. Creating a $resource Factory for API Integration

Example: Define a $resource for User API

app.factory('UserService', function($resource) {
return $resource('https://api.example.com/users/:id', { id: '@id' }, {
update: { method: 'PUT' },
delete: { method: 'DELETE' }
});
});

Explanation:

  • The API endpoint is 'https://api.example.com/users/:id', where :id is a dynamic placeholder for user ID.
  • update and delete methods are explicitly defined ($resource defaults POST for saving).

3. Using $resource in Controllers

Fetch All Users (GET Request)

app.controller('UserController', function($scope, UserService) {
$scope.users = UserService.query(); // Returns an array of users
});

What Happens?

  • .query() automatically makes a GET https://api.example.com/users.
  • The response is stored in $scope.users.

Fetch a Single User (GET by ID)

$scope.user = UserService.get({ id: 1 });

What Happens?

  • .get({ id: 1 }) makes a GET https://api.example.com/users/1.

Create a New User (POST Request)

var newUser = new UserService();
newUser.name = "John Doe";
newUser.email = "john@example.com";
newUser.$save();

What Happens?

  • .$save() makes a POST https://api.example.com/users with user data.

Update a User (PUT Request)

var user = UserService.get({ id: 2 }, function() {
user.name = "Updated Name";
user.$update();
});

What Happens?

  • Fetches user with GET https://api.example.com/users/2.
  • Calls .$update() → Sends a PUT request to update user details.

Delete a User (DELETE Request)

UserService.delete({ id: 3 });

What Happens?

  • delete({ id: 3 }) makes a DELETE https://api.example.com/users/3.

4. Advanced Configuration

Custom Actions in $resource

You can define custom API actions inside $resource.

app.factory('UserService', function($resource) {
return $resource('https://api.example.com/users/:id', { id: '@id' }, {
update: { method: 'PUT' },
delete: { method: 'DELETE' },
search: { method: 'GET', url: 'https://api.example.com/users/search', isArray: true }
});
});

Explanation:

  • update: { method: 'PUT' } → Defines PUT for updating users.
  • delete: { method: 'DELETE' } → Defines DELETE for removing users.
  • search: { method: 'GET', url: 'https://api.example.com/users/search', isArray: true }
    → Calls a custom search API and expects an array of results.

5. Full Implementation Example

var app = angular.module('myApp', ['ngResource']);

// Define User Service
app.factory('UserService', function($resource) {
return $resource('https://api.example.com/users/:id', { id: '@id' }, {
update: { method: 'PUT' },
delete: { method: 'DELETE' },
search: { method: 'GET', url: 'https://api.example.com/users/search', isArray: true }
});
});

// User Controller
app.controller('UserController', function($scope, UserService) {
// Get All Users
$scope.users = UserService.query();

// Get Single User
$scope.user = UserService.get({ id: 1 });

// Create User
$scope.addUser = function() {
var newUser = new UserService();
newUser.name = "John Doe";
newUser.email = "john@example.com";
newUser.$save();
};

// Update User
$scope.updateUser = function() {
var user = UserService.get({ id: 2 }, function() {
user.name = "Updated Name";
user.$update();
});
};

// Delete User
$scope.deleteUser = function(id) {
UserService.delete({ id: id });
};

// Search Users
$scope.searchResults = UserService.search({ query: 'John' });
});

6. Key Differences: $resource vs $http

Feature$resource$http
API Call StructureDeclarative (UserService.get(), UserService.save())Manual ($http.get(), $http.post())
Code ComplexityLess (Encapsulated in a factory)More (Repeated logic for every call)
Data BindingReturns resource objectsReturns plain promises
CustomizationCustom API endpoints can be addedFully customizable but needs more code

Leave a Reply

Your email address will not be published. Required fields are marked *