luibot
luibot

Reputation: 27

Retrieve from multiple APIs using Node Js and parsing it over to EJS files

Hello guys I am currently having trouble trying to solve this so I am working with https://newsapi.org/ APIs trying to pull from multiple sources but I am currently having trouble coming up with a way & parsing it over to the EJS I can do it for one api source but not for multiple is this even possible.

This is what I have managed to come up with so far

    app.get("/", function(req, res){
    request("https://newsapi.org/v1/articles?source=the-new-york-times&sortBy=top&apiKey=70a5906f19f844f291cff401c80bc123", function(error, response,body){
        if(! error && response.statusCode == 200) {
            var data = JSON.parse(body);
            res.render("results", {data: data});
        }
    });
});

Upvotes: 0

Views: 889

Answers (1)

styfle
styfle

Reputation: 24610

You can make a separate function that fetches data from a URL and returns a Promise. When the promise resolves, it will have the JSON object. Then you can render the data however you like.

Here is an example where I fetch 3 results from three different URLs. I am using Promise.all to wait for the response of all 3 requests before manipulating the data.

function fetchJSON(url) {
  return new Promise((resolve, reject) => {
    request(url, function(err, res, body) {
      if (err) {
        reject(err);
      } else if (res.statusCode !== 200) {
        reject(new Error('Failed with status code ' + res.statusCode));
      } else {
        resolve(JSON.parse(body));
      }
    });
  });
}

app.get("/", function(req, res) {
  const p1 = fetchJSON('http://example.com/one');
  const p2 = fetchJSON('http://example.com/two');
  const p3 = fetchJSON('http://example.com/three');

  Promise.all([p1, p2, p3]).then((data) => {
    res.render("results", {
      data_one: data[0],
      data_two: data[1],
      data_three: data[3]
    });
  }).catch(err => console.error('There was a problem', err));
});

Note that you could do whatever you want with the data array. I split it into three separate properties during rendering to show that there truly are 3 results.

Upvotes: 1

Related Questions