How to call a JSON API with Node.js?

Sometimes, we want to call a JSON API with Node.js.

In this article, we’ll look at how to call a JSON API with Node.js.

How to call a JSON API with Node.js?

To call a JSON API with Node.js, we can use the http module.

For instance, we write

const url = 'http://graph.facebook.com/517267866/?fields=picture';

http.get(url, (res) => {
  let body = '';

  res.on('data', (chunk) => {
    body += chunk;
  });

  res.on('end', () => {
    const fbResponse = JSON.parse(body);
    console.log("Got a response: ", fbResponse.picture);
  });
}).on('error', (e) => {
  console.log("Got an error: ", e);
});

to call http.get with a url to make a request to the URL.

Then we get the response from res.

And then we call res.on with 'data' to listen to the data event that we get from the chunk.

We concatenate the chunks to body to get the whole response body.

The whole response body should be available in the 'end' event callback since we concatenated the chunks to body.

Conclusion

To call a JSON API with Node.js, we can use the http module.