Aditya P
Aditya P

Reputation: 19

Passing the data from a POST API request to lambda function

I needed help with an issue that I am facing in order to meet the below requirement:

Requirement: 1. Submit form data from an HTML form through POST method to API gateway to a lambda function. One of the parameters in the email address. 2. Pass the parameters from the POST request to the lambda function. Lambda function should send out an email to the recipient via SES

Issue: I am able to hit the lambda function via POST call, but I am not able to pass the variables.

Test case: For testing the functionality, I have hardcoded the recipient address so that I get an email whenever the lambda function is hit. I am trying to pass the 'name' parameter and have the body of the email respond - Hi 'name'. Currently, I get the response- Hi undefined.

Below is the code I am using

// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
var aws = require('aws-sdk');
var ses = new aws.SES({ region: 'us-west-2' });

exports.handler = (event, context, callback) => {
  const emailbody = JSON.parse(event.body)
  var params = {
    Destination: {
      ToAddresses: 
    },
    Message: {
      Body: {
        Text: {
          Data: "Hi" + JSON.stringify(emailbody.name)
        }
      },
      Subject: {
        Data: "Test Email from lambda"
      }
    },
    Source: "[email protected]"
  };

  ses.sendEmail(params, function (err, data) {
    callback(null, { err: err, data: data });
    if (err) {
      console.log(err);
      context.fail(err);
    } else {
      console.log(data);
      context.succeed(event);

Reference: https://aws.amazon.com/premiumsupport/knowledge-center/lambda-send-email-ses/

I tried to pass the variable directly via event.name as well, but I wasn't successful in inserting the variable.

// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
var aws = require('aws-sdk');
var ses = new aws.SES({ region: 'ap-south-1' });

exports.handler = (event, context, callback) => {
//  const emailbody = JSON.parse(event.body);
  var params = {
    Destination: {
      ToAddresses: ["[email protected]"]
    },
    Message: {
      Body: {
        Text: {
          Data: "Hi" + JSON.stringify(event.name)
        }
      },
      Subject: {
        Data: "Test Email from lambda"
      }
    },
    Source: "[email protected]"
  };

  ses.sendEmail(params, function (err, data) {
    callback(null, { err: err, data: data });
    if (err) {
      console.log(err);
      context.fail(err);
    } else {
      console.log(data);
      context.succeed(event);
        }
    });
};

I am very new to the development and API world. Any help would be appreciated :)

Event Body

{"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9","Accept-Encoding":"gzip, deflate, br","Accept-Language":"en-US,en;q=0.9","cache-control":"max-age=0","CloudFront-Forwarded-Proto":"https","CloudFront-Is-Desktop-Viewer":"true","CloudFront-Is-Mobile-Viewer":"false","CloudFront-Is-SmartTV-Viewer":"false","CloudFront-Is-Tablet-Viewer":"false","CloudFront-Viewer-Country":"JP","content-type":"application/x-www-form-urlencoded","Host":"8x4r6h1ko3.execute-api.ap-south-1.amazonaws.com","origin":"null","sec-fetch-mode":"navigate","sec-fetch-site":"cross-site","sec-fetch-user":"?1","upgrade-insecure-requests":"1","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36","Via":"2.0 1eaa44d3cb0c85af04bf84d0f0c5256f.cloudfront.net (CloudFront)","X-Amz-Cf-Id":"z5idar1dflmmUP7OeYfF6lc70fTpb9_hOeZHjDaNkVKVyy31tB8u_Q==","X-Amzn-Trace-Id":"Root=1-5e173941-6ad68db372cf676f8268bfa7","X-Forwarded-For":"126.51.226.203, 64.252.167.136","X-Forwarded-Port":"443","X-Forwarded-Proto":"https"},"multiValueHeaders":{"Accept":["text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"],"Accept-Encoding":["gzip, deflate, br"],"Accept-Language":["en-US,en;q=0.9"],"cache-control":["max-age=0"],"CloudFront-Forwarded-Proto":["https"],"CloudFront-Is-Desktop-Viewer":["true"],"CloudFront-Is-Mobile-Viewer":["false"],"CloudFront-Is-SmartTV-Viewer":["false"],"CloudFront-Is-Tablet-Viewer":["false"],"CloudFront-Viewer-Country":["JP"],"content-type":["application/x-www-form-urlencoded"],"Host":["8x4r6h1ko3.execute-api.ap-south-1.amazonaws.com"],"origin":["null"],"sec-fetch-mode":["navigate"],"sec-fetch-site":["cross-site"],"sec-fetch-user":["?1"],"upgrade-insecure-requests":["1"],"User-Agent":["Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"],"Via":["2.0 1eaa44d3cb0c85af04bf84d0f0c5256f.cloudfront.net (CloudFront)"],"X-Amz-Cf-Id":["z5idar1dflmmUP7OeYfF6lc70fTpb9_hOeZHjDaNkVKVyy31tB8u_Q=="],"X-Amzn-Trace-Id":["Root=1-5e173941-6ad68db372cf676f8268bfa7"],"X-Forwarded-For":["126.51.226.203, 64.252.167.136"],"X-Forwarded-Port":["443"],"X-Forwarded-Proto":["https"]},"queryStringParameters":null,"multiValueQueryStringParameters":null,"pathParameters":null,"stageVariables":null,"requestContext":{"resourceId":"mmrduj26lk","resourcePath":"/","httpMethod":"POST","extendedRequestId":"GCXiOG99BcwFkdA=","requestTime":"09/Jan/2020:14:31:29 +0000","path":"/POST_Dev_Test","accountId":"856365680740","protocol":"HTTP/1.1","stage":"POST_Dev_Test","domainPrefix":"8x4r6h1ko3","requestTimeEpoch":1578580289353,"requestId":"010988e0-4598-4e88-af41-de42fa0b607e","identity":{"cognitoIdentityPoolId":null,"accountId":null,"cognitoIdentityId":null,"caller":null,"sourceIp":"126.51.226.203","principalOrgId":null,"accessKey":null,"cognitoAuthenticationType":null,"cognitoAuthenticationProvider":null,"userArn":null,"userAgent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36","user":null},"domainName":"8x4r6h1ko3.execute-api.ap-south-1.amazonaws.com","apiId":"8x4r6h1ko3"},"body":"name=Tera&email=aditya.prakash%40psyora.com","isBase64Encoded":false}

Warm Regards, Adi

Upvotes: 1

Views: 2434

Answers (1)

Arun Kamalanathan
Arun Kamalanathan

Reputation: 8593

What you have is a query string. The query is string is where you pass the value as key=value&key2=value2

  • When you test it from API gateway, you should add the query strings under the section called Query Strings instead of Request Body

    • In your case the query string is:

      name=Tera&email=aditya.prakash%40psyora.com
      
    • You should access it inside the lambda as event. queryStringParameters.name:

  • Your event.body contains the value name=Tera&email=aditya.prakash%40psyora.com which means your form is posted as x-www-form-urlencoded. Thats the type of form submission from html forms, therefore in your case, you need to decode the encoded string in your lambda.

    const qs = require('querystring')
    
    exports.handler = (event, context, callback) => {
      const parsedQueryString = qs.parse(event.body)
      const name = parsedQueryString.name
    }
    

Hope this helps.

Upvotes: 3

Related Questions