Calling JSON API and manipulating result with Node.js

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
_>npm install node-fetch

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’);
var _URL = {
authority: ‘https://’,
host: 'cloud.iexapis.com',
endpoint: '/stable/stock/',
quote: 'aapl',
parameters: '/quote?',
api: 'token=[PLACE YOUR TOKEN HERE]'
};
for(i=0; i < quoteList.length; i++){
url = _URL.authority +
_URL.host +
_URL.endpoint +
quoteList[i] +
_URL.parameters +
_URL.api;
urls.push(url)
}

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);
});
fetch(url)
.then(response => {
return response.json();
})
.then(data => {
Object.keys(data).forEach( key => {
console.log(`${key} : ${data[key]}`);
});
})
symbol : AAPL
companyName : Apple Inc
primaryExchange : NASDAQ/NGS (GLOBAL SELECT MARKET)
latestPrice : 126.655
latestSource : Close
latestTime : December 18, 2020
latestUpdate : 1608325201311

Full Stack Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store