$http service for making API requests

Loading

In AngularJS, the $http service is used to make AJAX requests to fetch, send, and update data from a remote server. It provides an easy-to-use interface for making API calls and handling responses asynchronously.

This guide will explain:
How $http works in AngularJS
How to make GET, POST, PUT, DELETE requests
Handling responses and errors
Best practices for using $http efficiently


1. Understanding the $http Service

The $http service in AngularJS is an XMLHttpRequest (XHR) wrapper, which provides methods to communicate with an API. It supports:
🔹 GET – Fetch data from the server
🔹 POST – Send new data to the server
🔹 PUT – Update existing data on the server
🔹 DELETE – Remove data from the server

Basic Syntax of $http

$http({
method: 'GET', // HTTP method (GET, POST, PUT, DELETE)
url: 'https://api.example.com/data' // API Endpoint
}).then(
function success(response) {
console.log(response.data); // Handle success response
},
function error(response) {
console.error(response.status); // Handle error response
}
);

2. Making API Requests Using $http

Let’s go through each HTTP method with examples.

2.1. GET Request – Fetching Data

The GET method retrieves data from a remote API.

Example – Fetching Users List

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

app.controller('UserController', function($scope, $http) {
$scope.users = [];

$http.get('https://jsonplaceholder.typicode.com/users')
.then(function(response) {
$scope.users = response.data; // Store data in scope
})
.catch(function(error) {
console.error('Error fetching data:', error);
});
});

HTML

<div ng-app="myApp" ng-controller="UserController">
<ul>
<li ng-repeat="user in users">
{{ user.name }} - {{ user.email }}
</li>
</ul>
</div>

How it works?

  • Sends a GET request to the JSONPlaceholder API
  • Fetches the list of users
  • Displays the data in the UI using ng-repeat

2.2. POST Request – Sending Data

The POST method is used to send new data to a server.

Example – Creating a New User

app.controller('UserController', function($scope, $http) {
$scope.newUser = {};
$scope.addUser = function() {
$http.post('https://jsonplaceholder.typicode.com/users', $scope.newUser)
.then(function(response) {
console.log('User added:', response.data);
})
.catch(function(error) {
console.error('Error adding user:', error);
});
};
});

HTML

<div ng-app="myApp" ng-controller="UserController">
<input type="text" ng-model="newUser.name" placeholder="Enter Name">
<input type="email" ng-model="newUser.email" placeholder="Enter Email">
<button ng-click="addUser()">Add User</button>
</div>

How it works?

  • User enters name & email in input fields
  • Clicking “Add User” sends data using POST

2.3. PUT Request – Updating Data

The PUT method is used to update existing data.

Example – Updating User Information

$scope.updateUser = function(userId) {
var updatedUser = {
name: "Updated Name",
email: "updated@email.com"
};

$http.put('https://jsonplaceholder.typicode.com/users/' + userId, updatedUser)
.then(function(response) {
console.log('User updated:', response.data);
})
.catch(function(error) {
console.error('Error updating user:', error);
});
};

HTML

<button ng-click="updateUser(1)">Update User</button>

How it works?

  • Updates user with ID = 1
  • Sends PUT request with new user details

2.4. DELETE Request – Removing Data

The DELETE method removes a record from the database.

Example – Deleting a User

$scope.deleteUser = function(userId) {
$http.delete('https://jsonplaceholder.typicode.com/users/' + userId)
.then(function(response) {
console.log('User deleted:', response.data);
})
.catch(function(error) {
console.error('Error deleting user:', error);
});
};

HTML

<button ng-click="deleteUser(1)">Delete User</button>

How it works?

  • Sends DELETE request to remove user with ID = 1

3. Handling Responses and Errors

The $http service returns a Promise (.then()) with two callbacks:
1️⃣ Success Callback – When API request is successful
2️⃣ Error Callback – When API request fails

Example – Handling API Errors Properly

$http.get('https://jsonplaceholder.typicode.com/users')
.then(function(response) {
console.log('Data:', response.data);
})
.catch(function(error) {
console.error('API Error:', error.status, error.statusText);
});

Best Practices for Handling Errors

  • Use .catch() to handle failed requests
  • Display meaningful error messages to users

4. Using $http in a Service (Best Practice)

Instead of writing $http requests in controllers, it’s better to create a service.

Example – User Service for API Requests

app.factory('UserService', function($http) {
return {
getUsers: function() {
return $http.get('https://jsonplaceholder.typicode.com/users');
}
};
});

app.controller('UserController', function(UserService) {
var vm = this;
UserService.getUsers().then(function(response) {
vm.users = response.data;
});
});

Why Use a Service?

  • Keeps controllers clean and focused on UI logic
  • Reusability$http logic is shared across the app

Leave a Reply

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