MyFirstAPICall

by arnaudlauret

HTML

<div id="title">My First API Call</div>

<pre id="apiCallResultStatus"></pre>
<pre id="apiCallResultData"></pre>

CSS

body {
  background: black;
  padding: 20px;
  font-family: Helvetica;
}

pre {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}


#title {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
  text-align: center;
}

JavaScript

/* 
  -----------------------------------------------------
  |      Not really interesting function for now.     |
  | You can jump direcly to line 35 to make API calls |
  -----------------------------------------------------
*/ 

function callSomeApi(httpMethod, url, body) {
	document.querySelector("#apiCallResultStatus").innerHTML = httpMethod + ' '+ url+ '\nLoading data...';
  // Preparing the apiClient
  let apiClient = new XMLHttpRequest();
  apiClient.open(httpMethod, url);
  apiClient.responseType = 'json';
  // Actually calls the API
  apiClient.send(JSON.stringify(body));
  // This will be called after the response is received
	apiClient.onload = function() {
    document.querySelector("#apiCallResultStatus").innerHTML = httpMethod + ' '+ url+ '\nHTTP Status: ' + apiClient.status + ' ' + apiClient.statusText;
    if(apiClient.response !== null)
	  	document.querySelector("#apiCallResultData").innerHTML = JSON.stringify(apiClient.response, undefined, 2);
    else
   		document.querySelector("#apiCallResultData").innerHTML = '(no data)'; 	
	};
  apiClient.onerror = function() {
  	document.querySelector("#apiCallResultData").innerHTML = 'An unexpected error occured';
	};
}

/*
  ----------------------------------
  | Interesting things starts here |
  |    Modify URL in callSomeApi   |
  ----------------------------------
*/
callSomeApi('GET', 'https://swapi.co/api/people/');

/*
  API that you can play with:
  
  - SWAPI (website: https://swapi.co)
  - Fire and Ice (website: https://anapioficeandfire.com)
  - Forex rates (website: https://exchangeratesapi.io/)
*/