Public
Edited
Jun 2, 2023
Importers
Insert cell
# Simple REST API Caller
Do GET and POST calls with a pre-formed url and get back JSON. Doesn't do any param handling, auth, etc.; callers will have to build that into the url. Some debug calls to console. Remember to add `await` before calls.
Insert cell
// Example - get a cat fact from public API
await callGetUrl("https://catfact.ninja/fact")
Insert cell
// Class wrapper for single import
class SimpleRestCaller {
constructor(name) { this.name = name; }
static getUrl(url, verbose = true) {
return callGetUrl(url, verbose)
}

static postUrl(url, jsonData, verbose = true) {
return callPostUrl(url, jsonData, verbose)
}
}
Insert cell
SimpleRestCaller.getUrl("https://catfact.ninja/fact")
Insert cell
function callGetUrl(url, verbose = true) {
if (verbose) console.log("GET " + url);
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
var dest = url;

xhr.open("GET", dest);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (verbose) {
console.log("Got response " + xhr.responseText);
console.log("Status " + xhr.status);
}

if (xhr.status != 200) {
reject("Error!");
}
resolve(JSON.parse(xhr.responseText));
}
};

try {
xhr.send();
} catch(e) {
if (verbose) console.log("Error " + e);
reject(e)
}
return "Doing GET on " + url
});
}
Insert cell
function callPostUrl(url, jsonData, verbose = true) {
if (verbose) console.log("GET " + url + " with data " + jsonData.toString());
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
var dest = url;

const data = JSON.stringify(jsonData);
if (verbose) console.log("Sending data " + data)
xhr.open("POST", dest);
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log("Got response " + xhr.responseText);
console.log("Status " + xhr.status);

if (xhr.status != 200) {
reject("Error!");
}
resolve(JSON.parse(xhr.responseText));
}
};

try {
console.log("Sending " + jsonData.toString());
xhr.send(data);
} catch(e) {
if (verbose) console.log("Error " + e);
reject(e)
}
return "Doing POST on " + url
});
}
Insert cell
{
var headers = [["one", "two"], ["three","four"]];
for(var h in headers) {
console.log(`value ${headers[h][0]}`)
}
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more