In this article, I will show how to call REST API in JQuery.

Complete source code can be found on GitHub repo at

https://github.com/sudipta-chaudhari/JQueryPromise_RestAPI

Use Case: Call GitHub GET API : https://api.github.com/users/sudipta-chaudhari (replace ‘sudipta-chaudhari’ with your GitHub username) and bind result in HTML page. Final output looks as below :

JQuery_GitHubRest

 

If must have used JQuery’s get() method that loads data from the server using a HTTP GET request. It’s syntax is as below:

$.get(URL,data,function(data,status,xhr),dataType)

Here, function is a callback function. JavaScript statements are executed line by line. With asynchronous code or effects, the next line of code can be run even though the asynchronous code hasn’t finished execution. This can create errors.To prevent this, you can create a callback function. A callback function is executed after the current asynchronous function or effect is finished.

You may wonder what is promise and as callback’s are present, why should be use promise’s.

Promise represents the result of a task, which may or may not have completed. The only interface requirement of a Promise is having a function called then, which can be given callbacks to be called when the promise is fulfilled or has failed.

JavaScript Promises use callback functions actually to specify what to do after a Promise has been resolved or rejected, so the two are not fundamentally different. The main idea behind Promises is to take callbacks – especially nested callbacks where you want to perform a series of actions, each one after the resolution of the former.

Let’s write some code to fetch the user details and user’s repository details from GitHub.

GitHub REST API’s used are as follows:

(1) https://api.github.com/users/

(2) https://api.github.com/users//repos

(3) https://api.github.com/repos//
Replace  with your GitHub username and  with your GitHub repository name and make a HTTP GET request to the API.

You can hit the above URL in your browser to see the result or you can use any REST Client tool to call the API. The result of the API call will be JSON.

GitHub_UserInfo_APICall_Result

In a HTML5 web page, I will call this API and display the results.

Create a root folder and under it, create two sub-folders named “Scripts” and “Styles”.

Under “Scripts” folder, download and save

Under “Styles” folder, download Bootstrap and save

At the time of writing, the latest versions available are Bootstrap v3.3.7, JQuery 3.2.1 and JQuery.BlockUI 1.33 which have been downloaded and used.

At the root folder, create a HTML file with the below contents.

<!DOCTYPE html>
<html>
<head>
    <script src="Scripts/jquery-3.2.1.js"></script>
    <script src="Scripts/jquery.blockUI.js"></script>
    <link rel="stylesheet" href="Styles/bootstrap.min.css" />
    <style type="text/css">
        .legend .row:nth-of-type(odd) div {
            background-color: #FFC300;
        }

        .legend .row:nth-of-type(even) div {
            background: #FF5733;
        }
    </style>

    <script>
        $(document).ready(function () {
            var userName = 'sudipta-chaudhari';

            $.blockUI();

            $.getJSON('https://api.github.com/users/' + userName)
            .then(function (userInfo) {
            //Get data from first api call
            getUserData(userInfo);
            //Get data from second api call
            return $.getJSON('https://api.github.com/users/' 
            + userName + '/repos').then(function (userRepos) {
            $.each(userRepos, function (key, val) {
            //Get data from third api call
            $.getJSON('https://api.github.com/repos/' 
            + userName + '/' + val.name).
            then(function (repoDetails) {
            $.getJSON('https://api.github.com/repos/' +   
            + userName + '/' + val.name).
            then(function (repoDetails) {
            $('#public_repos').append(
            "<b>" + val.name + "</b>;
            Created At : " + repoDetails.created_at +
            "; Updated At : " + repoDetails.updated_at + "<br />");
            });
            });
            });
            }).fail(function (error) {
                 $('.error').append(error.status + " : " + error.statusText);
            }).always(function () {
                 $.unblockUI();
            });

            function getUserData(userInfo) {
                $('#id').append(userInfo.id);
                $('#name').append(userInfo.name);
                $('#blog').append(userInfo.blog);
                $('#location').append(userInfo.location);
                //$('#public_repos').append(userInfo.public_repos);
                $('#created_at').append(userInfo.created_at);
                $('#updated_at').append(userInfo.updated_at);
            }
        });
    </script>
</head>
<body>
<div class="container legend">
     <div class="row">
          <div class="col-md-2">ID</div>
          <div id="id" class="col-md-8"></div>
     </div>
     <div class="row">
          <div class="col-md-2">Name</div>
          <div id="name" class="col-md-8"></div>
     </div>
     <div class="row">
          <div class="col-md-2">Blog</div>
          <div id="blog" class="col-md-8"></div>
     </div>
     <div class="row">
          <div class="col-md-2">Location</div>
          <div id="location" class="col-md-8"></div>
     </div>
     <div class="row">
          <div class="col-md-2">Public Repos</div>
          <div id="public_repos" class="col-md-8"></div>
      </div>
      <div class="row">
          <div class="col-md-2">Created At</div>
          <div id="created_at" class="col-md-8"></div>
      </div>
      <div class="row">
          <div class="col-md-2">Updated At</div>
          <div id="updated_at" class="col-md-8"></div>
      </div>
</div>
<div class="error" style="background-color:red"></div>
</body>
</html>

In this HTML page, first three lines under head section JQuery, JQuery.blockUI and Bootstrap CSS files have been referenced.

Next, under the style tag, a custom css class “legend” has been added which adds color to every even and odd rows of the resulting HTML.

Next, a script tag has been defined which starts JQuery’s ready() function.

The first line under script tag defines a variable to store the GitHub username. The next line calls blockUI() function to block the UI till the HTTP GET request using getJSON() function of JQuery defined in next line finishes execution.

getJSON() function makes a HTTP GET request to the GitHub REST URL for getting user details. The then() method allows us to modify the result of a promise and pass it to the next handler in the chain.  The real power of promises comes from chaining multiple of them together. Calling promise.then(func) returns a new promise, which is not fulfilled until func has completed. But there’s one really special thing about the way func is used. If a callback supplied to then returns a new promise, then the promise returned by then will not be fulfilled until the promise returned by the callback is fulfilled.

In out code, there is a single promise returned in the then() function. In then() function, response is received from the HTTP GET api url and the below JSON result fields are appended to the various DIV’s using Jquery’s ID selector as:

$('#id').append(userInfo.id);
$('#name').append(userInfo.name);
$('#blog').append(userInfo.blog);
$('#location').append(userInfo.location);
//$('#public_repos').append(userInfo.public_repos);
$('#created_at').append(userInfo.created_at);
$('#updated_at').append(userInfo.updated_at);

If error(s) encountered during HTTP GET request, fail function displays the error status and error status text in a div tag which has a Bootstrap css class .error applied.

The next function always() is executed irrespective of the success or failure of the HTTP GET request. It’s like a finally block of C#.

In the html body tag, div tags are defined which are used to display the various fields of the JSON result from the HTTP GET request.

The first $.getJSON code has been commented and has been replaced by the $.getJSON code below which shows chaining of two REST API calls. The first REST API call https://api.github.com/users/sudipta-chaudhari completes and then the next REST API call https://api.github.com/users/sudipta-chaudhari/repos is made. Thankfully, promises and deferred objects are implemented natively in the $.getJSON method.

Second api call fetches the names of all the user’s repositories after the first api call completes execution. The result of “Public Repos” section comes from the nested api call.

Inside the $.each loop, third api is called to fetch the details of each GitHub repository’s created and updated date.

Below code segments highlights the chaining of the two api calls and the third api call inside $.each loop.

$.getJSON('https://api.github.com/users/' + userName)
    .then(function (userInfo) {
        //Get data from first api call
        getUserData(userInfo);
        //Get data from second api call
        return $.getJSON('https://api.github.com/users/' + userName + '/repos')
            .then(function (userRepos) {
                $.each(userRepos, function (key, val) {
                    //Get data from third api call
                    $.getJSON('https://api.github.com/repos/' + userName + '/' + val.name).then(function (repoDetails) {
                        $('#public_repos').append("(" + (key + 1) + ") " + val.name + "; Created At : " + repoDetails.created_at
                            + "; Updated At : " + repoDetails.updated_at + "
");
                    });
                });
            })
    })
    .fail(function (error) {
        $('.error').append(error.status + " : " + error.statusText);
    })
    .always(function () {
        $.unblockUI();
    });

JQuery $.each has been used to loop through multiple results of the second api call which are the names of the multiple repositories and append them to the div with id ‘public_repos’.

Opening the HTML page in the browser, till the HTTP GET request completes, the output looks as below:

JQuery_GET_Pg1

After the HTTP GET request completes, the output looks as below:

 

I hope you followed the article. If you have any comments, questions or suggestions, leave a message and I will try to respond at my earliest.