Background
Many times you need to make an external API call from your Node.js application. A simple example would be calling an API gateway from you Node.js based Lambda in your AWS environment. In this post, I will show you two ways to do this -
- The standard http/https library
- The request library
Using the standard http/https library
Let's see how we can use the standard http library to make an API request.
To use standard http or https library you can simply import the module using -
const https = require("https"); const http = require("http");
Now you can use these to make your http or https calls. A sample is provided below -
/** * Node.js code to demonstrate https calls. * @author athakur */ const https = require("https"); var startDemo = function () { console.log("starting demo code"); executeHttps(function (err, data) { if (err) { console.log("Error in running demo code"); } else { console.log("Successfully ending demo code"); } }); } var executeHttps = function (callback) { var options = { hostname: "opensourceforgeeks.blogspot.com", port: 443, path: "/p/about-me.html", method: 'GET', headers: { 'Content-Type': 'text/html' } }; var req = https.request(options, function (res) { console.log("Status for API call : " + res.statusCode); console.log("Headers for API call : " + JSON.stringify(res.headers)); res.setEncoding('utf8'); var body = ''; res.on('data', function (chunk) { body = body + chunk; }); res.on('end', function () { console.log("Body for API call : " + body.length); if (res.statusCode != 200) { console.log("API call failed with response code " + res.statusCode); callback("API call failed with response code " + res.statusCode, null) } else { console.log("Got response : " + body.length); callback(null, body); } }); }); req.on('error', function (e) { console.log("problem with API call : " + e.message); callback(e, null); }); req.end(); } startDemo();
You can get this code on my Github gist as well - https://gist.github.com/aniket91/2f6e92a005eb2a62fcc1ddd39aac6dc2
To execute just run (Assuming your file name is test.js) -
- node test.js
You can similarly do it for http as well. For http you need to use -
- const https = require("http");
- change port to 80 in options
- call http.request instead of https.request
Similarly, you can execute POST method. Change options to -
var options = { hostname: "opensourceforgeeks.blogspot.com", port: 80, path: "/p/about-me.html", method: 'POST', headers: { 'Content-Type': 'text/html', 'Content-Length': Buffer.byteLength(post_data) } };
and then before you close request using req.end(); add
- req.write(post_data);
Now that we have seen how http/https modules work in nodejs let's see how request module works.
Using the request library
Request module is more user-friendly to use.To begin with, you need to install request module dependency since it is not a standard library that comes with nodejs. To install execute the following command -
- npm install request
You should see a folder called node_modules getting created in your directory with the request and other dependent modules getting installed.
You can import request module using -
- const request = require('request');
Then you can use it as follows -
/** * Node.js code to demonstrate https calls. * @author athakur */ const request = require('request'); var startDemo = function () { console.log("starting demo code"); executeRequest(function (err, data) { if (err) { console.log("Error in running demo code"); } else { console.log("Successfully ending demo code"); } }); } var executeRequest = function(callback){ var headers = {} headers['Content-type'] = 'text/html' //console.log('Payload for refresh_token: ', querString.stringify(payload)) request({ url: 'https://opensourceforgeeks.blogspot.com//p/about-me.html', method: 'GET', headers: headers }, function (err, response, body) { if (err) { console.error('API failed : ', err) callback(err) } else { console.log("Statuscode: " + response.statusCode); console.log("Got response : " + body.length); callback(null, body); } }) }
And the output is -
You can execute POST call as well by changing method type to POST. Eg -
request({ url: 'https://opensourceforgeeks.blogspot.com//p/about-me.html', method: 'POST', body: payload, headers: headers }, function (err, response, body) { if (err) { console.error('API failed : ', err) callback(err) } else { console.log("Statuscode: " + response.statusCode); console.log("Got response : " + body.length); callback(null, body); } });
Hope this helps! Let me know if you have any questions. Thanks.
Related Links
- How to install Node and npm to run node.js programs in Linux(OSFG)
- https://gist.github.com/aniket91/2f6e92a005eb2a62fcc1ddd39aac6dc2
- https://www.npmjs.com/package/request
- https://nodejs.org/api/https.html
for the post method im getting and error saying that payload is undefined
ReplyDelete