Retrieve JSON from RESTful API using fetch/XHRs

Example: Use JS to fetch data from RESTful API server

We may need access to a large selection of data, and a raw database may be either too large to tag onto the source, or contain private information (email addresses, account numbers, etc.) we shouldn't expose. In this case, the best solution is retrieving data from a third party RESTful API server.

Provided an api endpoint url and an authentication key, we can make calls to the API. We then recieve a JSON payload, effectively providing a senstive value for a  key via API.

Below is an anonymized example of retrieving a user's balance by passing an email address to the API. This solution keeps us from having an explicit js object listing user email addresses in the page's source code.

function ssGetJSON(address, successHandler, errorHandler){
var endpoint = 'https://api.server.com/records?emailaddress=' + address;
var authKey= "yourrandomlookingauthkey123456789==";
var xhr = new XMLHttpRequest();
xhr.open("GET", enpoint);
xhr.responseType = 'json';
xhr.onreadystatechange = function(){
var status;
var data;
if (xhr.readyState === 4){
status = xhr.status;
document.querySelector("#ssModal-inner").style.backgroundColor = "#e8ede6";
document.querySelector("#ssModal-inner").style.backgroundImage = "none";
if (status == 200){
data = xhr.response;
successHandler && successHandler(data);
} else{
errorHandler && errorHandler();
}
}
};
xhr.setRequestHeader("Authorization", authKey);
xhr.send();
}

function displayInfo(data){
var elem = document.getElementById("ssModal");
var amt = data[0].amount;
elem.innerHTML = '<h1 class="ssText1">The Amount is: '+amt+':</h1>';
}

function doSomethingelse(){
console.error("There was an error!");
}

ssGetJSON(jexample@sitespect.com, displayInfo, doSomethingElse);