简体   繁体   中英

How to handle POST request with Lambda Proxy Integration and API Gateway REST

I read a lot of topics about how to handle POST requests with Lambda Proxy Integration from AWS, but no one of them helps me to solve my issue.

I read that if we are using a Lambda Proxy Integration the post body have to be like this:

 { "body": "{\"name\":\"Mickael2\"}" }

Here is my Lambda function (very basic):

const AWS = require('aws-sdk')
const dynamoDB = new AWS.DynamoDB({ region: 'eu-west-3'})

const { v4: uuidv4 } = require('uuid');

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

    const body = JSON.parse(event.body).body;

    const name = JSON.parse(body).name;
    
    let uuid = uuidv4();
    
    let response = {
        statusCode: 200,
        headers: {
            'x-custom-header': 'My Header Value',
        },
        body: JSON.stringify({})
    };
    
  
   const params = {
      Item: {
       "id": {
         S: uuid
        }, 
       "name": {
         S: name
        }
    }, 
    TableName: "Users3"
 };
   
 dynamoDB.putItem(params, function(err, data) {
  if (err){
      console.log(err, err.stack); 
      cb(null, response);
  }
  else{
      console.log(data);
      response.body = JSON.stringify({name:name, uuid: uuid })
      cb(null, response);
  }      
 });
 
  
};

For example when i am trying to give this body:

{ 
    "name":"Mickael"
}

And doing console.log(event.body) i am getting:

{ "name": "Mickael" }

But when I am trying to get access to event.body.name i am getting undefined

Does someone have any other way to work with Post request on Lambda Proxy Integration? Thanks.

I see that you are using the Lambda function to push into DynamoDB. Since you're asking about other ways to handle it, if this Lambda function isn't doing anything else (and assuming you're using API Gateway to kick off the Lambda Function), my recommendation is to skip Lambda altogether and just go directly from APIGateway to DynamoDB. In your APIGW Integration Request , set it to use AWS Service instead of Lambda, then select DynamoDB as the service, Set the HTTP Method to POST , and set the Action to PutItem . And for the Integration Request Mapping Template , build out that same JSON as you are doing above {Item: {"id": {S: uuid}, "name": {S: name}}, TableName: "Users3"} .

I read that if we are using a Lambda Proxy Integration the post body have to be like this:

 { "body": "{\"name\":\"Mickael2\"}" }

Depends what you mean by "post body", is that what you're sending or what you're receiving? If you're sending it, you can structure it however you want. If you're receiving it (ie in the lambda function), the structure will be as in your example, ie a body key in the event object, containing the stringified payload.

const body = JSON.parse(event.body).body;

If you're parsing the body, and the body is "{\"name\":\"Mickael2\"}" (ie stringified payload), then there is no body key/property on the resultant object, and therefore const body === undefined .

If you actually sent { body: "{\"name\":\"Mickael2\"}" } as the payload, which you shouldn't, then that code is valid.

const name = JSON.parse(body).name;

Depending on the actual payload, body is either an object, undefined, or a string at this point. If it's an object or undefined then parsing it again should throw an exception. If it's not doing so then perhaps it's because you are in fact supplying a payload of { body: "{\"name\":\"Mickael2\"}" } , in which case that code is valid, but as stated it's the wrong way to send the payload.

Your payload should be:

{
  name: "Mickael2"
}

When it goes through proxy integration into your lambda, the event object will look like so (irrelevant bits removed):

{
  body: "{\"name\":\"Mickael2\"}"
}

So this is how you should handle it in your lambda:

const payload = JSON.parse(event.body);
const name = payload.name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM