This example demonstrates how to get data from an external API and how to separate that data using a function node. We will use data from an external API that provides access to earthquake data which is made available by the US geological survey (USGS). (http://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php)
First, let’s wire the flow like this:
Figure 6.19 Flow to query USDG earthquake data
Let’s edit the http request to get data from the following url as shown below (Fig 6.20):
http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_month.geojson
This data contains significant earthquakes from the last month. The JSON node after the request will allow you to parse the body of the response into an object usable by the following function.
Figure 6.20 Setting up a http request node to query USDG earthquake data
Now edit the function node and add the code shown in Fig 6.21:
This code will create an array (outputMsgs) containing an array of messages built from your data. The for loop goes through the received JSON response and creates a new message with a payload containing lat, lng, value, message and timestamp values (only a few values from the JSON object sent from the server). It will then push this new message object to the outputMsgs array.
It will create a new variable (msg2) with a new message object containing a payload element with the string “Second Output”.
Finally, the function will return an array containing two elements. The first element is an array of messages (outputMsgs); the second element is a single message (msg2). Let’s configure the function to have 2 outputs, to match our returned array.
Figure 6.21 Function node code to query USDG earthquake data
When you click the button on the inject node, you can see that the top output contains an array of messages parsed from the data. This corresponds to the outputMsgs array in the function (See Fig. 6.22).
Figure 6.22 First output from the flow that queries USDG earthquake data
The second output contains the single message (msg2):
Figure 6.23 Second output from the flow that queries USDG earthquake data
BACK to main Lecture 6