Integrating third-party APIs in an AngularJS application allows developers to fetch and send data to external services like Google Maps, OpenWeather, Stripe, PayPal, Firebase, and RESTful APIs.
In this guide, you’ll learn how to:
Make GET and POST requests using $http
and $resource
Handle API authentication with API keys and JWT tokens
Implement error handling and retries
Optimize performance with caching
1. Setting Up API Calls in AngularJS
Step 1: Create an AngularJS App
First, set up a simple AngularJS application.
var app = angular.module("apiApp", []);
2. Using $http Service for API Requests
AngularJS provides the $http
service for making AJAX requests.
Step 2: Fetch Data from an API (GET Request)
Example: Fetching data from a public API (JSONPlaceholder).
app.controller("ApiController", function ($scope, $http) {
$scope.posts = [];
$http.get("https://jsonplaceholder.typicode.com/posts")
.then(function (response) {
$scope.posts = response.data; // Store response data in scope
})
.catch(function (error) {
console.error("Error fetching posts:", error);
});
});
Displaying the Data in HTML
<div ng-app="apiApp" ng-controller="ApiController">
<h3>Posts from API</h3>
<ul>
<li ng-repeat="post in posts">
<strong>{{ post.title }}</strong>: {{ post.body }}
</li>
</ul>
</div>
3. Sending Data to an API (POST Request)
To send data, use a POST request.
Step 3: Submit Data to an API
Example: Sending a new post to an API.
app.controller("PostController", function ($scope, $http) {
$scope.newPost = {
title: "",
body: ""
};
$scope.submitPost = function () {
$http.post("https://jsonplaceholder.typicode.com/posts", $scope.newPost)
.then(function (response) {
console.log("Post submitted:", response.data);
alert("Post added successfully!");
})
.catch(function (error) {
console.error("Error submitting post:", error);
});
};
});
Form for Submitting Data
<div ng-app="apiApp" ng-controller="PostController">
<h3>Submit a Post</h3>
<input type="text" ng-model="newPost.title" placeholder="Title" /><br />
<textarea ng-model="newPost.body" placeholder="Body"></textarea><br />
<button ng-click="submitPost()">Submit</button>
</div>
4. Handling API Authentication
Many APIs require API keys or JWT tokens for authentication.
Step 4: Using API Keys
Some APIs require an API key in the request headers.
$http.get("https://api.example.com/data", {
headers: { "Authorization": "Bearer YOUR_API_KEY" }
})
Step 5: Using JWT Tokens
For authentication with JWT (JSON Web Token):
$http.post("https://api.example.com/login", {
username: "user",
password: "pass"
}).then(function (response) {
localStorage.setItem("token", response.data.token);
});
For sending authenticated requests:
$http.get("https://api.example.com/data", {
headers: { "Authorization": "Bearer " + localStorage.getItem("token") }
});
5. Handling API Errors Gracefully
Step 6: Implementing Error Handling
$http.get("https://api.example.com/data")
.then(function (response) {
console.log("Success:", response.data);
})
.catch(function (error) {
console.error("Error:", error);
if (error.status === 401) {
alert("Unauthorized! Please log in.");
}
});
6. Using $resource for RESTful APIs
Instead of $http
, AngularJS provides $resource
for working with RESTful APIs.
Step 7: Install ngResource
npm install angular-resource
Add it as a module:
var app = angular.module("apiApp", ["ngResource"]);
Step 8: Define a Resource
app.factory("PostService", function ($resource) {
return $resource("https://jsonplaceholder.typicode.com/posts/:id", { id: "@id" });
});
Step 9: Fetch Data Using $resource
app.controller("PostController", function ($scope, PostService) {
$scope.posts = PostService.query(); // Fetch all posts
});
7. Making Parallel API Calls Using $q.all()
To fetch multiple APIs at the same time, use $q.all()
.
Step 10: Fetch Multiple API Calls in Parallel
app.controller("MultiApiController", function ($scope, $http, $q) {
var usersRequest = $http.get("https://jsonplaceholder.typicode.com/users");
var postsRequest = $http.get("https://jsonplaceholder.typicode.com/posts");
$q.all([usersRequest, postsRequest]).then(function (responses) {
$scope.users = responses[0].data; // Users data
$scope.posts = responses[1].data; // Posts data
}).catch(function (error) {
console.error("Error in API calls:", error);
});
});
8. Caching API Responses Using $cacheFactory
Caching helps reduce unnecessary API calls.
Step 11: Enable API Caching
app.factory("ApiService", function ($http, $cacheFactory) {
var cache = $cacheFactory("apiCache");
return {
getData: function () {
return $http.get("https://api.example.com/data", { cache: cache });
}
};
});
9. Optimizing API Calls
Step 12: Debouncing API Requests
If a user types in an input field, prevent excessive API calls.
<input type="text" ng-model="searchQuery" ng-model-options="{ debounce: 500 }" />