0

I am trying to integrate a POST API call from a lambda function using Node.js 12.x.

I tried like below:

var posturl = "My post api path";
var jsonData = "{'password':'abcdef','domain':'www.mydomain.com','username':'abc.def'}";
var req = require('request');
const params = {
    url: posturl,
    headers: { 'jsonData': jsonData }
};
req.post(params, function(err, res, body) {
    if(err){
        console.log('------error------', err);
    } else{
        console.log('------success--------', body);
    }
});

But when I am execute it using state machine, I am getting the below exception:

{
  "errorType": "Error",
  "errorMessage": "Cannot find module 'request'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
  "trace": [
    "Error: Cannot find module 'request'",
    "Require stack:",
    "- /var/task/index.js",
    "- /var/runtime/UserFunction.js",
    "- /var/runtime/index.js",
    "    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)",
    "    at Function.Module._load (internal/modules/cjs/loader.js:667:27)",
    "    at Module.require (internal/modules/cjs/loader.js:887:19)",
    "    at require (internal/modules/cjs/helpers.js:74:18)",
    "    at Runtime.exports.handler (/var/task/index.js:8:14)",
    "    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
  ]
}

Here the posturl is my api path and jsondata is my key value pair data.

So How can I call a POST API from lambda function? How can I pass the entire jsondata key when call API? How can I parse the response after the service call?

Update: I have tried like below

All my details are passing with a key jsonData, where I can specify that? Without that key, it will not work.

exports.handler = (event, context, callback) => {
    const http = require('http');
    const data = JSON.stringify({
    password: 'mypassword',
    domain: 'www.mydomain.com',
    username: 'myusername'
});

const options = {
    hostname: 'http://abc.mydomain.com',
    path: 'remaining path with ticket',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
    }
};

const req = http.request(options, (res) => {
    let data = '';

    console.log('Status Code:', res.statusCode);

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

    res.on('end', () => {
        console.log('Body: ', JSON.parse(data));
    });

}).on("error", (err) => {
    console.log("Error: ", err.message);
});

req.write(data);
req.end();  
};
Matthew Pans
  • 223
  • 1
  • 3
  • 12
  • check out this answer [AWS Lambda HTTP POST Request (Node.js)](https://stackoverflow.com/a/57293327/2246345) – samtoddler Feb 02 '21 at 11:06

1 Answers1

0

source : How to Make an HTTP Post Request using Node.js

const https = require('https');

const data = JSON.stringify({
    name: 'John Doe',
    job: 'Content Writer'
});

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


const req = https.request(options, (res) => {
    let data = '';

    console.log('Status Code:', res.statusCode);

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

    res.on('end', () => {
        console.log('Body: ', JSON.parse(data));
    });

}).on("error", (err) => {
    console.log("Error: ", err.message);
});

req.write(data);
req.end();
samtoddler
  • 8,463
  • 2
  • 26
  • 21
  • @MatthewPans you are making an `http` request and `importing https`. For sharing code samples you can use [gists](https://gist.github.com/). `Keep your project related details private.` – samtoddler Feb 02 '21 at 12:55
  • I have added my post api path on `hostname`and `path` sections. And added the username, password and domain name under the data section. But all these datas are collectively added as a json data with key `jsonData`. Where we can add that key? Could you please elaborate the answer with these points. Please don't post private url and data, just put some dummy data instead of that. – Matthew Pans Feb 02 '21 at 12:57
  • @MatthewPans the url and ticket details I saw. If they are not something you wanna protect, that's fine. – samtoddler Feb 02 '21 at 12:59
  • @MatthewPans try this [gist](https://gist.github.com/toddlers/c89958d9a3db93a75c42c9a6a678dfc2) – samtoddler Feb 02 '21 at 13:14
  • I have edited the question with how I have tried, could you please check the update1 section of question. – Matthew Pans Feb 04 '21 at 11:10
  • Hello, any update? I am still not able to call the post api from lambda function. – Matthew Pans Feb 08 '21 at 09:58
  • @MatthewPans I am not able to test the solution yet. – samtoddler Feb 08 '21 at 16:59
  • I need to know about only one thing, where we are passing the body? – Matthew Pans Feb 13 '21 at 11:22