Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call rest api inside aws lambda function using nodejs

i have created aws lambda function. i want to use rest api calls inside my lambda function. Is there any reference how to connect it to rest api using nodejs

like image 598
praveen Dp Avatar asked Jul 24 '18 06:07

praveen Dp


3 Answers

const https = require('https')

// data for the body you want to send.
const data = JSON.stringify({
  todo: 'Cook dinner.'
});

const options = {
  hostname: 'yourapihost.com',
  port: 443,
  path: '/todos',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  },
};

const response = await doRequest(options, data);
console.log("response", JSON.stringify(response));

/**
 * Do a request with options provided.
 *
 * @param {Object} options
 * @param {Object} data
 * @return {Promise} a promise of request
 */
function doRequest(options, data) {
  return new Promise((resolve, reject) => {
    const req = https.request(options, (res) => {
      res.setEncoding("utf8");
      let responseBody = "";

      res.on("data", (chunk) => {
        responseBody += chunk;
      });

      res.on("end", () => {
        resolve(JSON.parse(responseBody));
      });
    });

    req.on("error", (err) => {
      reject(err);
    });

    req.write(data);
    req.end();
  });
}
like image 113
Dhanuka Perera Avatar answered Oct 11 '22 13:10

Dhanuka Perera


If you want to call rest api inside lambda function, you can use request package:

install request package via npm: https://www.npmjs.com/package/request

Then inside lambda function try this to call rest api:

    var req = require('request');
    const params = {
        url: 'API_REST_URL',
        headers: { 'Content-Type': 'application/json' },
        json: JSON.parse({ id: 1})
    };
    req.post(params, function(err, res, body) {
        if(err){
            console.log('------error------', err);
        } else{
            console.log('------success--------', body);
        }
    });
like image 33
Eduardo Díaz Avatar answered Oct 11 '22 14:10

Eduardo Díaz


const superagent = require('superagent');

exports.handler =  async(event) => {
    return await startPoint();  // use promise function for api 
}


function startPoint(){
    return new Promise(function(resolve,reject){
    superagent
    .get(apiEndPoint)
    .end((err, res) => {
        ...



       });
    })
}
like image 44
aknamdeo Avatar answered Oct 11 '22 14:10

aknamdeo