Using $resource for RESTful APIs

Loading

In AngularJS, $http is commonly used to interact with RESTful APIs. However, managing repeated API calls with $http requires extra code for methods like GET, POST, PUT, and DELETE. The $resource service simplifies this by providing a higher-level abstraction for working with RESTful services.


1. What is $resource?

$resource is part of AngularJS’s ngResource module and provides an easier way to interact with REST APIs. It automatically handles:
Mapping endpoints to JavaScript methods
CRUD (Create, Read, Update, Delete) operations
Query parameters and URL placeholders
Simplified request handling

🔹 Before using $resource, make sure you include the ngResource module in your app.

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

2. Setting Up $resource

To use $resource, inject the $resource service into a factory or controller.

Example: Basic $resource Setup

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

🔹 This creates a UserService that interacts with the /users API.
🔹 The :id in the URL is a dynamic placeholder that will be replaced with actual user IDs when making requests.
🔹 The update method is defined using PUT, as $resource does not include it by default.


3. Performing CRUD Operations with $resource

a) Fetching All Users (GET)

app.controller("UserController", function($scope, UserService) {
$scope.users = UserService.query(); // Fetches a list of users
});

🔹 .query() makes a GET request to /users and returns an array of users.


b) Fetching a Single User (GET)

$scope.user = UserService.get({ id: 1 }); // Fetches user with ID 1

🔹 .get({ id: 1 }) makes a GET request to /users/1.


c) Creating a New User (POST)

var newUser = new UserService();
newUser.name = "John Doe";
newUser.email = "john@example.com";
newUser.$save(); // Sends a POST request to create a new user

🔹 Calling $save() sends a POST request to /users with the new user data.


d) Updating a User (PUT)

var user = UserService.get({ id: 1 }, function() {
user.name = "Updated Name";
user.$update(); // Sends a PUT request to update user ID 1
});

🔹 The update method (defined in $resource setup) is used for modifying user data.


e) Deleting a User (DELETE)

UserService.delete({ id: 1 }); // Sends DELETE request to /users/1

🔹 .delete({ id: 1 }) removes the user with ID 1.


4. Custom Actions in $resource

You can define custom methods inside $resource with different HTTP methods.

Example: Adding a Custom search Method

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

🔹 .search() makes a GET request to /users/search instead of /users.
🔹 isArray: true ensures the response is an array of users.


5. Handling API Responses (Success & Error)

You can handle success and error cases using .then() or .catch().

UserService.get({ id: 1 }).$promise.then(
function(response) {
console.log("User fetched successfully:", response);
},
function(error) {
console.error("Error fetching user:", error);
}
);

🔹 $resource methods return a promise that can be handled using .then() for success and .catch() for errors.


6. $resource vs. $http – Which One to Use?

Feature$resource$http
Simplifies CRUD operations Yes No
Requires manual data transformation No Yes
Supports promises natively Yes Yes
Handles query parameters easily Yes No
Better for complex API calls No Yes

Use $resource for simple CRUD-based REST APIs.
Use $http when you need fine-grained control over requests, responses, and transformations.

Leave a Reply

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