Why Should You Use a GitHub API?

Spread the love

Using Git, the popular Version Control System, Use a GitHub API is one of the best places to collaborate on software and discover new projects (VCS).

GitHub is an important part of the Open Source Software movement. So, it constantly pushes the boundaries of technology as we know it by enabling developers to contribute to more projects and network with other developers.

GitHub has also created an awesome API for us to use when developing applications, and the good news is that it’s very simple to get started.

This tutorial has been updated to send network requests using (the more traditional) fetch method rather than XMLHttpRequest.

If you prefer to use XMLHttpRequest, please follow the original tutorial here.

Making use of the GitHub API

Let’s look at how we can start with GitHub’s REST API. A comprehensive list of GitHub endpoints is available here.

The GET /users/rep.os. The Endpoint will be used in today’s example to list all public repositories for the specified parameter. So, this is a simple API endpoint with which we will experiment.

We can enter the url below into a web browser and view some data.

Please test it out: https://api.github.com/users/timmywheels/repos

So, if everything went as planned, you should see the first 30 public repositories for my GitHub username, timmywheels. Try using your GitHub username instead if you’re feeling brave!

id: 136095779,
node_id: “MDEwO1J1cG9zaXRvcnkxMzYwOTU3Nzk=”, name: “agile-week”,
full_name: “timwheelercom/agile-week,” private: false,

  • owner: {
    },
    login: “timwheelercom,”
    id: 17229444,
    node_id: “MDQ6VXNlcjE3MjI5NDQ0”,
    avatar_url:
    “https://avatars1.githubusercontent.com/u/17229444?v=4”,
    gravatar_id: “, “
    url: “https://api.github.com/users/timwheelercom”, html_url: “https://github.com/timwheelercom”,
    followers_url:
    “https://api.github.com/users/timwheelercom/followers,”
    following_url: “https://api.github.com/users/timwheelercom/following/other_user).”, gists_url: “https://api.github.com/users/timwheelercom/gists{/gist_id}”, starred_url: “https://api.github.com/users/timwheelercom/starred{/owner}{/repo}.”, subscriptions_url: “https://api.github.com/users/timwheelercom/subscriptions”, organizations_url: “https://api.github.com/users/timwheelercom/orgs”, repos_url: “https://api.github.com/users/timwheelercom/repos”,
    events_url: “https://api.github.com/users/timwheelercom/events{/privacy.}”,
    received_events_url: “https://api.github.com/users/timwheelercom/received_events,” type: “User”,
    site_admin: false

Pasting this URL into a browser just works because the browser implicitly sends an HTTP GET request when a URL is entered. Pretty cool!

p.s. I’m using the JSONView then Chrome Extension to pretty-print the JSON output in my browser.

Getting Resources from the GitHub API Making use of fetch

There are several methods for requesting data asynchronously from a backend server, but we’ll use the built-in JavaScript fetch method today. Then getting started with fetch is fairly simple.

An earlier version of this post requested backend resources using XMLHttpRequest, but fetch is far more common.

Make a Function to Call the GitHub API

First and foremost, let’s write a simple function that will eventually wrap the fetch request to GitHub’s /users/repos, where it is a variable.

Given that it is dynamic, we must pass a username argument to our function.

function requestUserRepos(username){
  // we'll fill this in later
}

To get data from GitHub, use fetch.

Let’s incorporate our fetch request into the function we just created.

function requestUserRepos(username){
    // call the fetch method, 
    // passing in the `username` arg to the request
    fetch(`https://api.github.com/users/${username}/repos`);
}

Managing Promises: Use a GitHub API

You would only see a little if you called requestUserRepos (some username) right now. Because fetch returns a promise, which is… [an] object [that] represents the eventual completion (or failure) because of an asynchronous operation and its resulting value.

Finally, a Promise ensures an asynchronous operation will complete at some unspecified point. Promises are especially useful when dealing with network requests because we need to know when the data from GitHub (or any API, for that matter) will be returned. Still, they provide a declarative way for our code to handle the various scenarios.

A Promise will always be in one of the following three states:

  • pending: The initial condition 
  • Fulfield: The operation was a success
  • Rejected: The operation was a failure.

Taking apart the Promise returned by fetch

There are several ways to use Promises in JavaScript. We’ll use the Promise.then() methods, which (admittedly) makes the code a little more verbose but allows us to work directly from the browser console.

        Async/ await syntax is generally preferred in today’s JavaScript landscape because it is more straightforward and easier to read. However, because this is an interactive tutorial designed to be followed through the browser console, I have decided to skip async/await because this tutorial will rely heavily on IIFEs (When using the PlayStation).

function requestUserRepos(username){
    // create a variable to hold the `Promise` returned from `fetch`
    return Promise.resolve(fetch(`https://api.github.com/users/${username}/repos`));
}

// call function, passing in any GitHub username as an arg
requestUserRepos('facebook')
  // parse response into json
  .then(response => response.json())
  // log response data
  .then(data => console.log(data));

Could you test it out in your browser’s console?

Viewing the Complete API Response

When you run the code above, you will get a response with an array of 30 objects. Because each object contains data about a specific repository. By default, GitHub’s API returns the first 30 repositories for that user in alphabetical order.

Awesome! We’re now utilizing the GitHub API. So, let’s keep things moving and see how we can access more information using the API request we’ve set up.

Iterating on the Payload: Use a GitHub API

Assume we wanted to get each repo’s name, description, and URL returned in the response payload.

When you expand the individual objects from the response payload, you’ll notice that they contain all the information we seek. In our case, we’ll want to extract the keys name, description, and html url from each object in the data array.

codesnippet-github-api-response-object

Instead of logging the entire data payload as we did previously, let’s be more deliberate and log the name, definition, and html url for each archive as follows:

// call function, passing in any GitHub username as an arg
requestUserRepos('facebook')
  // parse response into json
  .then(response => response.json())
  // iterate through parsed response
  .then(data => {
    for (let i in data) {
      // Log the repo name
      console.log('Repo:', data[i].name);

      // Log the repo description
      console.log('Description:', data[i].description);

      // Log the repo url
      console.log('URL:', data[i].html_url);

      // Add a separator between each repo
      console.log('=========================') 
    }
})

So, what now?

Now that we’ve configured our GitHub API request, we’d naturally like to show it to our application’s users somewhere other than the browser console. How do we go about doing that?

Creating a Simple GitHub API Example Application

Let’s create a simple project that displays the data of the specified username directly on our webpage.

1. Create a directory on your desktop called github-api.

Let’s make a directory called github-api on our desktop to hold the files for our simple API example application.

2. Add the index.html file to the github-api directory.

The HTML markup for our web app will be contained in this file.

3. Add the file app.js to the github-api directory.

This file will contain the code we just wrote. We’ll make changes until it displays the requested data on the webpage.

Our index.html document

This one will be relatively simple. Some basic HTML boilerplate includes an h3, a form, a ul, and a link to the app.js file.

We’ll also import the Bootstrap CSS Library and apply a few Bootstrap classes to our HTML elements to make things interesting.

Bootstrap is not required to get your GitHub app working, but we’ll include it in our project to make it look half-decent.

We’ll make use of the Bootstrap CSS CDN:

The CDN documentation can be found at https://getbootstrap.com/docs/4.1/getting-started/introduction/.

We’ll use the following Bootstrap classes:

For each class, I’ve included links to the corresponding sections of the Bootstrap documentation.

•.text-center | Used for text alignment | 

  • View Documentation.mt-5,.mx-auto,.mb-5,.m1-2 | Used for margins | 
  • View Documentation. form-inline | Used for making form fields inline | 
  • View Documentation. form-control | Used for form field appearance |
  • View Documentation. btn | Used for button appearance | 
  • View Documentation. Btn-primary Documentation
  • Modifier class for button appearance | View. list-group 
  • View Documentation. list-group-item | General unordered list item styling | 
  • View Documentation I Please keep in mind that the. List-group-item class is only used in app.js, not index.html.

To clarify, the. List-group-item class is only used in app.js and not in index.html.

Overall, I’ve added little to the Bootstrap classes to this app, but I wanted to ensure you started on the right foot. You can certainly put your spin on things and truly make them your own from here.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>GitHub API</title>

	<!-- Import the Bootstrap CSS CDN -->
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

</head>
<body>

	<h3 class="text-center mt-5">GitHub API</h3>
	<form id="gitHubForm" class="form-inline mx-auto" style="width: 280px">
		<input id="usernameInput" class="form-control mb-5" type="text" name="username" placeholder="GitHub Username">
		<input type="submit" class="btn btn-primary ml-2 mb-5" value="Submit">
	</form>
	<ul id="userRepos" class="list-group mx-auto mb-5" style="width: 500px">

	</ul>
	
	<script src="app.js"></script>
</body>
</html>

Our application.js file

This will be mostly the same as the previous code. The main difference will be that we must retrieve the user’s input from the GitHub username form and pass it into our earlier requestUserRepos() function.

Then we must attach the data from our API request to the DOM. We can accomplish this by grabbing a ul with an ID of user Repos and appending the data as li’s within the ul from within the for-loop within the final.then() method on requestUserRepos. So, let’s see how it goes:

// Get the GitHub username input form
const gitHubForm = document.getElementById('gitHubForm');

// Listen for submissions on GitHub username input form
gitHubForm.addEventListener('submit', (e) => {

    // Prevent default form submission action
    e.preventDefault();

    // Get the GitHub username input field on the DOM
    let usernameInput = document.getElementById('usernameInput');

    // Get the value of the GitHub username input field
    let gitHubUsername = usernameInput. Value;

    // Run GitHub API function, passing in the GitHub username
    requestUserRepos(gitHubUsername)
        // resolve promise then parse response into json
        .then(response => response.json())
        // resolve promise then iterate through json
        .then(data => {
            // update html with data from github
            for (let i in data) {
                // Get the ul with id of userRepos

                if (data.message === "Not Found") {
                    let ul = document.getElementById('userRepos');

                    // Create variable that will create li's to be added to ul
                    let li = document.createElement('li');

                    // Add Bootstrap list item class to each li
                    li.classList.add('list-group-item')
                    // Create the html markup for each li
                    li.innerHTML = (`
                <p><strong>No account exists with username:</strong> ${gitHubUsername}</p>`);
                    // Append each li to the ul
                    ul.appendChild(li);
                } else {

                    let ul = document.getElementById('userRepos');

                    // Create variable that will create li's to be added to ul
                    let li = document.createElement('li');

                    // Add Bootstrap list item class to each li
                    li.classList.add('list-group-item')

                    // Create the html markup for each li
                    li.innerHTML = (`
                <p><strong>Repo:</strong> ${data[i].name}</p>
                <p><strong>Description:</strong> ${data[i].description}</p>
                <p><strong>URL:</strong> <a href="${data[i].html_url}">${data[i].html_url}</a></p>
            `);

                    // Append each li to the ul
                    ul.appendChild(li);
                }
            }
        })
})

function requestUserRepos(username) {
    // create a variable to hold the `Promise` returned from `fetch`
    return Promise.resolve(fetch(`https://api.github.com/users/${username}/repos`));
}

Using Our GitHub API App

We should be ready to go now that we’ve completed all of our code for the front-end markup, our API request, and some Bootstrap styling.

So, you only need to open the index.html file in your browser. Because on a Mac, double-click the file or right-click > Open With > Google Chrome.

Our Simple App User Interface

And there you have it! Here’s the result of all of our efforts. Because this will give you a solid foundation to build and expand your app.

Enter your GitHub username here.

Now comes the exciting part. Enter your GitHub username or one from Facebook, AirBnB, ReactJS, or my own – timmywheels.

When I typed in Facebook, this is what I got:

Hacker, congratulations!

You have successfully created a web application so, that queries the GitHub API and displays dynamic data to users on the browser’s front end! That’s some really cool stuff.

courtesy of GIPHY

Source code in its entirety

Then here’s a link to the tutorial’s working source code: https://github.com/timmywheels/github-api-tutorial

If you prefer to use the more verbose XMLHttpRequest, go to https://github.com/timmywheels/github-api- tutorial/tree/original.

16 thoughts on “Why Should You Use a GitHub API?”

Leave a Comment