Make rest api call using https node module.

REST (Representational State Transfer) is a popular architectural style for building web services. It allows clients to interact with a server using a simple set of commands, such as GET, POST, PUT, and DELETE. In this article, we will explore how to use the HTTPS module in Node.js to make REST API calls to a server.

First, we need to import the HTTPS module into our Node.js project by using the following code:

const https = require('https');

Once we have imported the HTTPS module, we can use it to make a REST API call to a server using the https.request() method. This method takes in an options object, which includes information such as the hostname and the endpoint of the API, and a callback function that will be executed when a response is received from the server.

Here is an example of how to use the HTTPS module to make a GET request to a REST API:

const https = require('https');

const options = {
  hostname: 'api.example.com',
  path: '/users',
  method: 'GET'
};

const req = https.request(options, (res) => {
  res.on('data', (data) => {
    console.log(JSON.parse(data));
  });
});

req.end();

In this example, we are making a GET request to the /users endpoint of the api.example.com server. The https.request() method returns a request object, which we can use to end the request by calling the req.end() method. The response from the server is passed to the callback function as a stream of data.

We can also make a POST request to a REST API using the HTTPS module. Here is an example of how to use the HTTPS module to make a POST request to a REST API:

const https = require('https');
const data = JSON.stringify({name: 'John Doe'});

const options = {
  hostname: 'api.example.com',
  path: '/users',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
};

const req = https.request(options, (res) => {
  res.on('data', (data) => {
    console.log(JSON.parse(data));
  });
});

req.write(data);
req.end();

In this example, we are making a POST request to the /users endpoint of the api.example.com server with a JSON payload containing a name. The Content-Type and Content-Length headers are added to the options object, and the request is written using the req.write() method before being ended using the req.end() method.

In conclusion, the HTTPS module in Node.js provides an easy-to-use API for making REST API calls to a server. By using the https.request() method, you can send GET, POST, PUT and DELETE requests with the correct options and handle the response in a callback. It’s a good practice to use https when making REST API calls as it ensures that the communication between the client and the server is secure.

Leave a Reply