Week 8 - Introduction to API's & JSON
Creating a server-side JSON feed for sharing data with other web apps. Example of consuming remote APIs.
APIs & JSON, because sharing is caring
Websites can make their data and services available to other servers and applications, this process is known as an API (application programming interface).
Many APIs today are basically URLs that give access to data and services from a given server. Your web sites can make use of these APIs to provide new content or create a mash up between different sets of data. You might even use an API to resize your photos or transcode your video. There are many uses but the easiest way to get started is to look at one.
JSON
JSON --> JavaScript Object Notation
Your NodeJS web applications can share data in JSON format to other web applications. Those web applications can be written in NodeJS, PHP, Ruby, Python. They can can running in OpenFrameworks or Processing. They can be front end JavaScript running in a browser.
var applePieRecipe = {
title : "Apple Pie",
ingredients : ['flour','butter','salt','sugar','apples','cinnamon','nutmeg'],
categories : ['pie','dessert','apples','harvest'],
cooking_time : "45 minutes"
};
console.log(applePieRecipe);
Converting NodeJS / Javascript objects to JSON
JSON is the serialized version of native JavaScript data types.
json_recipe = JSON.stringify(applePieRecipe);
// in ExpressJS we can send JSON very easily
res.json(applePieReceipt);
Result is a JSON string
"{
"title":"Apple Pie",
"ingredients":["flour","butter","salt","sugar","apples","cinnamon","nutmeg"],
"categories":["pie","dessert","apples","harvest"],
"cooking_time":"45 minutes"
}"
JavaScript Data Type Review
Strings - in quotes
"I'm a string"
Numbers - no quotes
42
Arrays - Square brackets with items separated by commas
['red','blue',42,true]
Objects - Curly brackets with key : value items separated by commas
{
name : 'Tony Pony',
age : 42,
city : 'New York'
}
Example JSON
Responding with JSON in Express
exports.data_all = function(req, res) {
// query for all astronauts
astroQuery = astronautModel.find({}); // query for all astronauts
astroQuery.sort('-birthdate');
astroQuery.exec(function(err, allAstros){
// prepare data for JSON
var jsonData = {
status : 'OK',
astros : allAstros
}
// send JSON to requestor
res.json(jsonData);
});
}
Requesting Remote JSON
We're using the Request module
Update your package.json
Add to 'dependencies' (be sure to add comma if needed)
"request" : "2.16.6"
Update NPM
In code directory in Terminal update npm with command...
npm install
Demo Index.js function
Add request to top of file
var request = require('request');
Function
exports.remote_api = function(req, res) {
var remote_api_url = 'http://itpdwdexpresstemplates.herokuapp.com/data/astronauts';
// var remote_api_url = 'http://localhost:5000/data/astronauts';
// make a request to remote_api_url
request.get(remote_api_url, function(error, response, data){
if (error){
res.send("There was an error requesting remote api url.");
}
// convert data JSON string to native JS object
var apiData = JSON.parse(data);
// if apiData has property 'status == OK' then successful api request
if (apiData.status == 'OK') {
// prepare template data for remote_api_demo.html template
var templateData = {
astronauts : apiData.astros,
rawJSON : data,
remote_url : remote_api_url
}
return res.render('remote_api_demo.html', templateData);
}
})
};
Assignment
Make some or all of your data available as JSON. Share your data JSON url on this class notes site. Describe the data and how it is collected and organized in JSON.
Step 2. Take another classmate's JSON feed and "consume" it. You should have a new route in your app, similar to /remote_api_test. Take in the remote JSON and redisplay it as an .html template.