Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Lambda, what type of request does the test button do?

AWS Lambda newbie here. I was doing some testing with AWS Lambda functions and there is something that it is not working correct for me. Given this lambda function:

exports.handler = async (event, context, callback) => {
    var response = {
        statusCode: 200,
        headers: {'Content-Type': 'application/json'},
        response: event.talk
    };
    callback(null, response);
};

When I press the test button with this content (here is a screenshot):

{
   "talk": "Hello World"
}

I get this response (here is a screenshot):

{
  "statusCode": 200,
  "headers": {
    "Content-Type": "application/json"
},
  "response": "Hello World"
}

But when I make a POST request (I added an open API gateway, see it here), it just returns empty data and sometimes internal server error (here is a screenshot):

no data

If I modify my Lambda function to JSON parse the body, it will work

exports.handler = async (event, context, callback) => {
    var body = JSON.parse(event.body);
    var talk = body.talk;
    var response = {
        statusCode: 200,
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(talk)
    };
    callback(null, response);
};

What it is happening? Why the test button work differently from a POST request? I want both to work, specially the test because I want to "debug" the "serverless"

like image 872
Lolpez Avatar asked Jul 18 '26 13:07

Lolpez


2 Answers

When You call AWS lambda handle request what you pass in the request.

So, When you need to pass data in event with body just add body params in event Object.

{
 "body": "{\"talk\":\"Hello World\"}"
}

Note:

When you Call lambda from POST then request Object contain body in the event.

like image 99
IftekharDani Avatar answered Jul 20 '26 22:07

IftekharDani


The test button will simply run your lambda with the event provided, but when you run it through API gateway proxy, you get an event in a different format. As to why it works when you parse event.body, it's because event.body will contain the message being sent through the API.

The best thing to do would be to do:

console.log(JSON.stringify(event));

And view the incoming event format.

like image 25
Deiv Avatar answered Jul 20 '26 23:07

Deiv



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!