Multiple ways to Call REST API from Nodejs Application| Consume REST API
Sometimes, the Application requires calling a Remote or external API from a nodejs Application.
It covers the following items
- How to call remote REST API from nodejs application
- How to get data from HTTP to get request data
- How to make HTTP get and post a request
- Get HTTP request body in nodejs
- Process post request in NodeJS
Nodejs is server-side code based on npm libraries.
Consume REST API involves HTTP request of type GET/POST/DELETE/PATCH
- HTTP/HTTPS inbuilt
- Axios
- fetch
It involves sending a request of json data and receiving the HTTP Response with
For calling any rest API, We need the following.
- REST API URL
- Request types like GET/POST/DELETE/PATCH
- HTTP request data type
- expected response type to handle it
- content-type and accept request headers
- Any security or authorization headers
How to make a call remote API using http/https module
http and HTTPS are inbuilt modules, that can be used as server and client
If the request url is https, We can use the https module, otherwise, use HTTP module Here is a syntax to make an HTTP url request
http.get( options, response callback);
http.post( options, responsecallback);
- First import using the
requiredkeyword - call
getmethod with Url and returns call back, which containsdataandendlisteners
data listener called when API return response successfull.
const http = require("https");
const url = "https://jsonplaceholder.typicode.com/posts";
http.get(url, function (response) {
let posts = "";
response.on("data", function (data) {
posts += data.toString();
});
response.on("end", function () {
console.log(posts.length);
console.log(posts.toString());
});
});
Axios HTTP Request example
Axios is a third part library that used to communicate with Http Request
