How to Use Public JSON APIs
We can query public databases and request data in the form of JSON. To learn about JSON read thisMDN guide to JSON data
JSON: (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.
API: (Application Program Interface) is a set of routines, protocols, and tools for building software applications. An API specifies how software components should interact.
Open a public JSON API URL in a new tab to see the data.
Example: http://anapioficeandfire.com/api/houses/378
Example: http://anapioficeandfire.com/api/characters/1303
JSON API lists:
https://github.com/toddmotto/public-apis
https://www.programmableweb.com/
https://data.nasa.gov/browse?limitTo=datasets
https://dev.socrata.com/consumers/getting-started.html
https://www.opendatanetwork.com/
Example Code
generic function to request JSON:
function loadJSON(path, success, error) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
calling the loadJSON function: (replace the URL)
loadJSON('http://api.open-notify.org/iss-now.json',
function(data) {
console.log(data)
},
function(xhr) {
console.error(xhr);
}
);
The JSON data is parsed into an object by the loadJSON function.
data {
iss_position: {
latitude: "-41.2572",
longitude: "-112.0342"
},
message: "success",
timestamp: 1490969278
}
No comments:
Post a Comment