GitHub API Example

by Khalid Alharbi

HTML

<header>
  <input id="inputBox" value="GitHub" type="text" placeholder="Enter any GitHub's user id">
  <button onclick=searchUsingXHR()>Search using XHR</button>
  <button onclick=searchUsingFetch()>Search using fetch</button>
  <button onclick=searchUsingFetchAwaitAsync()>Search using fetch with await/async</button>
</header>
<h2 id="title"></h2>
<img id="profileImage">
<samp id="sampleOutput"></samp>

CSS

samp {
  white-space: pre-wrap;
  background: hsl(30, 80%, 90%);
}

img {
  width: 200px;
  height: 200px;
  display: block;
  margin-bottom: 20px;
}

JavaScript

function searchUsingXHR() {
    var userId = document.getElementById("inputBox").value;
    var sampElem = document.getElementById("sampleOutput");
    var titleElem = document.getElementById("title");
    var profileImageElem = document.getElementById("profileImage");

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        // When the request is successful, finished, and response is ready
        if (this.readyState == 4 && this.status == 200) {
            sampElem.innerHTML = xhr.responseText;
            var responseObj = JSON.parse(xhr.responseText);
            profileImageElem.src = responseObj.avatar_url;
            titleElem.innerText = responseObj.login;
        }
    };
    // Send an asynchronous HTTP GET request to the given end point (url)
    xhr.open("GET", "https://api.github.com/users/" + userId, true);
    xhr.send();
}

function searchUsingFetch() {
    var userId = document.getElementById("inputBox").value;
    var sampElem = document.getElementById("sampleOutput");
    var titleElem = document.getElementById("title");
    var profileImageElem = document.getElementById("profileImage");

    fetch("https://api.github.com/users/" + userId)
        .then(response => {
            return response.json()
        })
        .then(data => {
            profileImageElem.src = data.avatar_url;
            titleElem.innerText = data.login;
            sampElem.innerHTML = JSON.stringify(data);
        })
}

async function searchUsingFetchAwaitAsync() {
    var userId = document.getElementById("inputBox").value;
    var sampElem = document.getElementById("sampleOutput");
    var titleElem = document.getElementById("title");
    var profileImageElem = document.getElementById("profileImage");

    let response = await fetch("https://api.github.com/users/" + userId);
    let data = await response.json();
    profileImageElem.src = data.avatar_url;
    titleElem.innerText = data.login;
    sampElem.innerHTML =...