Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express and Nodejs : Best way to call an external API

I am new to Express and Nodejs. I am trying to call an external api for building data on a page. Is there a way to call the external api from express itself (I know i can use http moduel to do this) but want to confirm is that the best way. Also once i get the json back how do i pass it to the view.

Right now i have done a workaround by just loading the view(just headers) with express and making an jquery ajax call to api and populate the data.

like image 745
SaNmm Avatar asked Aug 15 '14 15:08

SaNmm


People also ask

How do you call an API in Node js?

The simplest way to call an API from NodeJS server is using the Axios library. Project Setup: Create a NodeJS project and initialize it using the following command. Module Installation: Install the required modules i.e. ExpressJS and Axios using the following command.

Is NodeJS best for API?

js is best for your API development needs. Node. js renders such wonderful support to developers for the development of API. A real-time API which is dynamic can be built using node.


2 Answers

First of all, you need to call your external API inside controller where you want to populate it. The best will be to use http module, it is pretty easy to use http://nodejs.org/docs/v0.4.10/api/http.html#http.get . After you get data, you just pass it to view like this:

http.get(options, function(data) {
    res.render('template', data);
});
like image 102
monkeyinsight Avatar answered Oct 24 '22 23:10

monkeyinsight


I would write an object to hide the details of this data fetching (http requests) and make the http calls using superagent (just because it's a nice lib).

This way you can:

  • Replace the http requests later if you decide to use something else.
  • Hide details like using the node-async as monkeyinsight suggested.
like image 22
Victor Avatar answered Oct 24 '22 23:10

Victor