Calling JSON API and manipulating result with Node.js

Fabio Brigati
3 min readDec 21, 2020

In this post I’ll guide you through the process of setting up your Node.js application and building the script to call a server API which returns a JSON object, and ultimately iterate through its contents.

Setup the Node.js Project

Let’s dive right into it and set your Node.js project. Inside your project directory, type the node package manager initializer:

 _>npm install

Ok, now let’s get a npm package that’ll help us deal with HTTP requests later on, namely, node-fetch.

_>npm install node-fetch

Great! Now lets get to the entrails of the script next, yummy!

Write the Javascript code

Within your project’s folder create a file (ie.: ‘fetchData.js’), and open it in your favorite Javascript IDE. Lets start off with including the packages that we’ll need throughout the code. We do this with the require method, like so:

const fetch = require(‘node-fetch’);
const fs = require(‘fs’);

As mentioned above, node-fetch package will help us manage HTTP requests in an easier fashion than using Node.js’ native XMLHttpRequest. While fs is a super easy-to-use native Node.js package which enables interaction with the file system.

At this point we can go ahead and build the URL skeleton that we’ll be using to request our data from the API. In this example we’re calling an API that provides stock price data.

var _URL = {
authority: ‘https://’,
host: 'cloud.iexapis.com',
endpoint: '/stable/stock/',
quote: 'aapl',
parameters: '/quote?',
api: 'token=[PLACE YOUR TOKEN HERE]'
};

Separating the URL in different parts as done above has its advantages. For example, if we wanted to iterate different stock prices from an array, we’d simply attribute a variable to the ‘quote’ property and execute asynchronous API calls. Along the following lines:

for(i=0; i < quoteList.length; i++){
url = _URL.authority +
_URL.host +
_URL.endpoint +
quoteList[i] +
_URL.parameters +
_URL.api;
urls.push(url)
}

Great, we’re almost there! Now we can call the fetch function to retrieve our data so we can chew and digest it.

Retrieving the data from the API

Below is an example of how we could go about retrieving a single fetch and discerning what is important for our application:

fetch(url)
.then(response => {
return response.json();
})
.then(data => {
Object.keys(data).forEach( key => {
console.log(`${key} : ${data[key]}`);
});
})
.catch(err => {
console.log(err);
});

Lets break down the above code in pieces and check out what’s happening.

fetch(url)
.then(response => {
return response.json();
})

In this piece the fetch method makes a HTTP request to the described ‘url’ address. The method returns a promise containing a response object which will be (hopefully) populated with the data we require. We call the json() method from the response object, which is a shortcut to getting our data parsed from the body property. And finally we return the result to the next callback function.

.then(data => {
Object.keys(data).forEach( key => {
console.log(`${key} : ${data[key]}`);
});
})

In this piece we get the keys of the JSON object returned by the previous function block, and iterate through to get a list of all key — value pairs. Our output will be similar to the following:

symbol : AAPL
companyName : Apple Inc
primaryExchange : NASDAQ/NGS (GLOBAL SELECT MARKET)
latestPrice : 126.655
latestSource : Close
latestTime : December 18, 2020
latestUpdate : 1608325201311

At this point, we can get the data we require and continue to process according to our application’s objectives. Hopefully this will get you started with Node.js API calls.

Until next time, thanks for reading!

--

--