Consuming GitHub API using Angular JS

Consuming GitHub API using Angular JS

Repository: https://github.com/angular/angular.js

What will I Learn?

In this tutorial, you will learn the following

  • Consume the github web service and get required data
  • Search for github users using a search form
  • Display results based on search input
  • Sort the search result of user repository
  • Use angular filters to format the result
  • Display a custom error message when data loading fails

Requirements

For this tutorial, you will need the following

Difficulty

  • Basic

Tutorial Content

Angular JS framework which started from google and now an open source project such that anyone is allowed to use it or contribute to the project. Working with angular JS gives you more flexibility and power while implementing your project. This tutorial allows us to use angular js to consume the github api available to us to get various details of a github user. In the course of the tutorial, we will be able to retrieve data from the api using a search form, display the information on our webpage and as well sort the user repository as we wish.

Step 1: Getting Started

To begin this course you will need to include the angular js script to the index.html file either using the cdn link or the angular.min.js file downloaded from Angular JS. Then include a blank js script for writing our own angular js codes.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>GitHub Api using Angular JS</title>
    <script src="js/angular.min.js" charset="utf-8"></script>
    <script src="js/script.js" charset="utf-8"></script>
  </head>
  <body>
    <h1>GitHub viewer</h1>
  </body>
</html>

To confirm if your angular js was added successfully, you should not see any error on your browser console

Step 2: Get Angular Js up and running

Angular js requires you to provide a ng-app attribute in your HTML form which is an angular directive. The ng-app stands for angular which triggers the angular js to function within your HTML form.

<!DOCTYPE html>
<html ng-app>
  <head>
    <meta charset="utf-8">
    <title>GitHub Api using Angular JS</title>
    <script src="js/angular.min.js" charset="utf-8"></script>
    <script src="js/script.js" charset="utf-8"></script>
  </head>
  <body>
    <h1>GitHub viewer</h1>
  </body>
</html>

Then we could actually try out a mathematical expression to see that it functions properly by typing {{ 453 / 3 }} anywhere within the body tag.

NOTE: The ng-app directive can appear anywhere within the html form but it will only function within the area where the ng-app directive is located.

Step 3: Getting details of a single user through the API

We first have create a directive in our blank js script file which allows us create a controller which is in-charger of a particular area of our html file. To create a directive, you call the angular.module() and give it a name and an empty array for dependencies. The controller is then built based on the app directive that has been created earlier. We begin the controller with a controller name MainCtrl, a single dependency $scope and then a function with $scope as a the only parameter.

(function(){
  // create a directive
  var app = angular.module("myApp", []);
  
  // creates a controller called MainCtrl
  app.controller('MainCtrl', ['$scope', function($scope) {}]);

})();

To sent the request to the github api server, we require the angular $http depency to help send the request and return a response back to the script for further processing. Every $http request returns a result called a promise which we will use to create other required functions based on the response and also if there's an error while executing.

// creates a controller called MainCtrl
  app.controller('MainCtrl', ['$scope','$http', function($scope, $http) {
// sends the request
  var promise = $http.get("https://api.github.com/users/chrix95");
  promise.then(onSuccess, onError);

  }]);

A request is sent to the github api and stored to a variable promise which on success, execute the onSuccess() but if there is an error, executes the onError(). This two functions currently do not exist, we will have to create it within the controller. The response gotten is attached to the dependency variable $scope based on the fact that the response is either a success or an error.

var onSuccess = function(response){
    $scope.user = response.data; // this returns a json
}

var onError = function(response) {
    $scope.error = "Could not fetch data";
}

To preview changes, we need to attach our controller to the html within the ng-app directive and display the result from our $http request. The request returns a JSON which we will select from view details to display such as the name of the user, location and image.

singleUser.JPG

NOTE:

  • If angular was unable to retrieve the information, our custom error message displays on the screen.
  • To see a list of the available detail that could be gottten, enter https://api.github.com/users/? into your browser, where ? stands for any github username.
  • The ng-src directive of the image tag, allows angular to first process the url of the image before it is displayed on your browser.
  • Check singleUser.js and singleUser.html for complete code snippet

Step 4: Create a form to search for GitHub users

The previous step allows us to get github users by changing the username in the $http.get() url. This step will show us how to get input from a form in our html and display the details of the user if it exist on github. To achieve this, we first create the form on our html and use the ng-model directive to pass the information from our html to the script for processing. The ng-submit directive sends the form details to the script once the submit button is click and then the search() in our JS script is executed to fetch the result.

<form ng-submit="search(username)">
      <input type="search" ng-model="username">
      <input type="submit" value="Submit">
 </form>

In our script, the search function uses a parameter username which is collected from the form and it is attached to the the $http.get url in order to fetch the user details for display.

$scope.search = function(username) {
    var promise = $http.get("https://api.github.com/users/" + username);
    promise.then(onSuccess, onError);
};

NOTE:

  • No changes needs to be made to the onSuccess() and onError(), the variablepromise and promise.then is placed within the search $scope so it executes once the submit button is clicked on the form.
  • Check searchUser.js and searchUser.html for complete code snippet

Step 5: Getting the repositories of searched GitHub user

Once we can finally use the search box to fetch user details, we can use the information to retrieve the user repository created on gihub with some features of the repository like stars, name, language and license of each repository.

To achieve this, we modify the onSuccess() to use the details retrieved to send a $http.get request to fetch the repositories of that user then another function onSearchResult() - which we will create in our script file, is invoked on success of the $http.get request. onSearchResult() gets the response in JSON form and stores it to $scope.repos for access in the html file.

$scope.search = function(username) {
    var promise = $http.get("https://api.github.com/users/" + username);
    promise.then(onSuccess, onError);
};

var onSuccess = function(response){
    $scope.user = response.data;
    var promise = $http.get($scope.user.repos_url);
    promise.then(onSearchResult, onError);
 }

var onSearchResult = function (response) {
    $scope.repos = response.data;
}

We need to modify our html file to view the changes effectively. We need to create a loop that goes through the data and populate our table.

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Stars</th>
            <th>Language</th>
            <th>license</th>
        </tr>
    </thead>
<tbody>
    <tr ng-repeat="repo in repos">
        <td>{{repo.name}}</td>
        <td>{{repo.stargazers_count}}</td>
        <td>{{repo.language}}</td>
        <td>{{repo.license.name}}</td>
    </tr>
</tbody>
</table>

NOTE:

  • The ng-repeat is a directive in angular js that acts as a foreach loop to display the retrieved data into a given area.
  • The value repo holds each repository available in repos. Then each td carries the values of each repository attribute such as the name, stars (represented as stargazer_count), language of the repository and license name.
  • To see a list of the available details or attributes that could be retrieved, enter https://api.github.com/users/?/repos into your browser, where ? stands for any github username.

STEP 6: Sort the search result of user repository

To achieve this, we create a select input on our html and use the ng-model directive to pass the information from our html to the script for processing. Once the value of the select box changes, it triggers the sorting of the repository table.

<select ng-model="orderSortBy">
    <option value="+name">Name</option>
    <option value="-stargazers_count" selected>Stars</option>
    <option value="+language">Language</option>
    <option value="+license">License</option>
</select>

<tr ng-repeat="repo in repos | orderBy: orderSortBy">

NOTE:

  • The + in front of the values indicate Ascending order and the - indicates Descending order.
  • we have to pass a filter orderBy through a "pipe" | into our ng-repeat with a variable name orderSortBy so that it changes the order once the select input changes value.

To make the sorting functional, we create a new $scope within our controller and give it a value which eventually changes as the select input changes.

$scope.orderSortBy = "-stargazers_count";

Proof of Work Done

I hope you find this tutorial very useful and you can access the complete code for this tutorial in the github repo.

H2
H3
H4
3 columns
2 columns
1 column
5 Comments