Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postman call to AWS API Gateway to trigger AWS lambda function not working

I have created an api, when called, triggers the lambda function, written in nodejs, to take the json(array of objects) and insert the data into dynamodb. For each object in the array, the function creates a PutRequest object and when finished calls the batchWriteItem function. When I test in the aws console everything works fine but when I try in postman I get a 500 error. I know that the event is different when coming from postman vs the console and you are supposed to reference "event.body" if you want to access the json however when I do that I get an error with event.body.ForEach: "Cannot read property 'forEach' of undefined" in the console and a 500 error in postman. Below is the code that works in the console

var dynamo = new AWS.DynamoDB({region: 'us-east-1',});

exports.handler = (event, context, callback) => {

  const done = (err, res) => callback(null, {
        statusCode: err ? '400' : '200',
        body: err ? err.message : res,

    });

  var params = {
      RequestItems: {
        "Lead": []
      }
  }

    event.forEach(x => {

      params.RequestItems.Lead.push({
        PutRequest: {
          Item: {
            "Address": {S: x.Address},
            "City": {S: x.City},
            "State": {S: x.State},
            "Zipcode": {S: x.Zipcode},
            "Owner_First_Name": {S: x.Owner_First_Name},
            "Owner_Last_Name": {S: x.Owner_Last_Name}
          }
        }
      })
    })

    dynamo.batchWriteItem(params, done);

};
like image 696
Skip Bassey Avatar asked Nov 20 '25 12:11

Skip Bassey


1 Answers

When the lambda receive the json body from api gateway, it will be passed as a json string.

To convert the json string to json, You need to parse the event.body.

const body = JSON.parse(event.body)

Then you can do body.forEach

Hope this helps

like image 193
Arun Kamalanathan Avatar answered Nov 22 '25 02:11

Arun Kamalanathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!