$http vs. $resource – When to use what?

Loading

In AngularJS, both $http and $resource are used for making HTTP requests, but they serve different purposes. Understanding their differences will help you choose the right tool for your project.


1. Overview

  • $http: A low-level service for making HTTP requests manually.
  • $resource: A higher-level abstraction for RESTful APIs.

When to Use $http?

✔ When making simple, one-time API requests.
✔ When you need full control over request handling.
✔ When you don’t need an object-oriented RESTful API.

When to Use $resource?

✔ When working with RESTful APIs that follow CRUD patterns.
✔ When you need an easier way to interact with backend models.
✔ When reducing boilerplate code for data models is a priority.


2. Using $http (Low-Level API Calls)

Basic $http Example

myApp.controller("HttpController", function ($scope, $http) {
$http.get("/api/users")
.then(function (response) {
$scope.users = response.data; // Success
})
.catch(function (error) {
console.error("Error fetching users:", error);
});
});

Pros of $http

More flexible – you can customize headers, request types, and responses.
Works with non-REST APIs (GraphQL, WebSockets, etc.).
Allows custom request handling (caching, interceptors, etc.).

Cons of $http

Requires manual request handling (you must handle data transformation and HTTP methods yourself).
Can lead to boilerplate code when performing repetitive API calls (CRUD operations).


3. Using $resource (Simplified REST API Calls)

To use $resource, include ngResource as a dependency:

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

Basic $resource Example

myApp.factory("UserService", function ($resource) {
return $resource("/api/users/:id", { id: "@id" }, {
update: { method: "PUT" } // Custom update method
});
});

Now, you can easily interact with the API:

myApp.controller("ResourceController", function ($scope, UserService) {
// Fetch all users
$scope.users = UserService.query();

// Fetch a single user
$scope.user = UserService.get({ id: 1 });

// Create a new user
var newUser = new UserService({ name: "Narendra" });
newUser.$save();

// Update user
$scope.user.name = "Updated Name";
$scope.user.$update();

// Delete user
$scope.user.$delete();
});

Pros of $resource

Less code – CRUD operations are built-in.
Object-oriented – You work with objects instead of raw API responses.
Automatic method mapping – Maps API actions (GET, POST, PUT, DELETE) to JavaScript methods.

Cons of $resource

Only works with RESTful APIs (not suitable for GraphQL or WebSockets).
Less flexible than $http (manual customization is harder).
Requires ngResource module, which increases dependency.


4. Key Differences Between $http and $resource

Feature$http (Low-Level)$resource (High-Level)
FlexibilityHigh (Fully customizable)Limited to RESTful APIs
Ease of UseRequires more codeSimplifies API calls
Object-OrientedNo, returns raw JSONYes, returns API models as objects
CRUD OperationsManual handlingBuilt-in support
Caching SupportRequires $cacheFactorySupports caching internally
Interceptor SupportYes, supports $httpInterceptorLimited support
Additional DependenciesNo extra module requiredRequires ngResource

5. When to Choose $http or $resource?

ScenarioRecommended
You need full control over API requests$http
API does not follow a standard REST structure$http
You’re using non-RESTful data sources (GraphQL, WebSockets)$http
You want a simple way to handle RESTful API requests$resource
You’re working with CRUD-based REST APIs$resource
You prefer object-oriented data handling$resource

Leave a Reply

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