rounak tadvi
rounak tadvi

Reputation: 29

How to perform post request using AWS's HTTP API?

I have a simple Nodejs Lambda function which is:

exports.handler = async (event) => {
  // TODO implement
  let key = event.key;
  const response = {
    statusCode: 200,
    body: 'Hello from Lambda! ' + key,
  };
  return response;
};

When I send the key using POSTMAN Via a POST Request, I get the following response :

Hello from Lambda! undefined

Upvotes: 0

Views: 810

Answers (2)

maithri vemula
maithri vemula

Reputation: 33

The event sent to lambda is of type object if sent from Postman. It is suggested to parse this object using JSON.parse(). Since this is coming from Postman as POST call, Postman wraps the request in body parameter. You need to extract the request from body in your lambda by event.body and parse it. If you test directly through Lambda console, you don't need to extract body as there is not wrapping. So make sure you do a check from where the request is coming from and type of request.

exports.handler = async (event) => {
          // TODO implement
    var request;
    if(event.body){
    console.log("Incoming request from postman");
          request = JSON.parse(event.body)
    }
    else{
    console.log("incoming request from lambda test event");
    request = event;
    }

           key = request.key;
          const response = {
            statusCode: 200,
            body: 'Hello from Lambda! ' + key,
          };
          return response;
        };

Upvotes: 1

jasonwalsh
jasonwalsh

Reputation: 846

The event object contains a body parameter which is the JSON string of the request payload.

Assuming your payload is:

{"key": "world"}

Then the following code should return Hello from Lambda! world:

let body = JSON.parse(event.body);
let key = body.key;

Upvotes: 1

Related Questions