How To Call API In AngularJS

In this article, we will learn about how we can call API in AngularJS.

API stands for Application Programming Interface. $http is an AngularJS service and can be used to read data from remote servers.

AngularJS $http

The $http service makes a request to the server and returns a response.

For calling the $http service there are several shortcut methods:

  • .get()
  • .delete()
  • .head()
  • .jsonp()
  • .patch()
  • .post()
  • .put()

Example

Open the Example1.html file and add the code in it.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
    <title></title>
</head>
<body>
    <div ng-app="myApp" ng-controller="myCtrl">
        <h1>API Response:</h1>
        <p>Status: {{status}}</p>
        <table border="1" width="100%">
            <tr>
                <th>ID</th>
                <th>Email</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Avatar</th>
            </tr>
            <tr ng-repeat="x in data">
                <td>{{x.id}}</td>
                <td>{{x.email}}</td>
                <td>{{x.first_name}}</td>
                <td>{{x.last_name}}</td>
                <td align="center"><img src="{{x.avatar}}" height="50px" /></td>
            </tr>
        </table>
    </div>
    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope, $http) {
            $http({
                method: "GET",
                url: "https://reqres.in/api/users"
            }).then(function Success(response) {
                $scope.data = response.data.data;
                $scope.status = "Success";
            }, function Error(response) {
                $scope.status = response.statusText;
            });
        });
    </script>
</body>
</html>

That’s it.

Output:

Submit a Comment

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

Subscribe

Select Categories