21

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

3
  • You just forget lambda function and call rest api using nodejs. Commented Jul 24, 2018 at 6:41
  • i am new to nodejs, is there any samples available for calling rest api using ngrok Commented Jul 24, 2018 at 6:56
  • 1
    Did you get a solution for this? If yes please update it as your answer. I am also trying to implement the same. Commented Jan 29, 2021 at 15:10

5 Answers 5

11

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();
  });
}

Sign up to request clarification or add additional context in comments.

Comments

3

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);
        }
    });

2 Comments

I tried this in lambda but doesn't work for me. where as same rest api work in postman and python script also.
Using this how we can pass the body data of the POST API? Also how we can parse the response of the service?
3

AWS Lambda now supports Node.js 18 ,which has support for global fetch , you can now easily call the REST api endpoints like this

// index.mjs 

export const handler = async(event) => {
    
    const res = await fetch('https://nodejs.org/api/documentation.json');
    if (res.ok) {
      const data = await res.json();
      console.log(data);
    }

    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

Comments

1
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) => {
        ...



       });
    })
}

Comments

-4

If you are asking about creating a HTTP rest endpoint in lambda using nodejs. Here is the example. https://github.com/serverless/examples/tree/master/aws-node-simple-http-endpoint

If you are asking about access an external API inside lambda using nodejs. Here is an example.

https://github.com/robm26/SkillsDataAccess/blob/master/src/CallService/index.js

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.