0

I'm writing a code that will connect API Gateway and DynamoDB. and they are as below.

Put Data

var body = JSON.parse(event.body);
    console.log(body.phone)
    var table = "userAddresses";
    var params = {
        TableName: table,
        Item: {
            "phone": body.phone,
            "apartmentNumber": body.apartmentNumber,
            "buildingNumber": body.buildingNumber,
            "state": body.state,
            "zip": body.zip
        }
    }

    docClient.put(params, function (err, data) {
        if (err) {
            console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
            var res = {
                "statusCode": 200,
                "headers": {},
                "body": JSON.stringify(data)
            };
            context.succeed(res);
        }
    });

Get Data

var body = JSON.parse(event.body);
    console.log(body.phone)
    var table = "userAddresses";
    var params = {
        TableName: table,
        Item: {
            "phone": body.phone
        }
    }
    docClient.get(params, function (err, data) {
        if (err) {
            console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
            var res = {
                "statusCode": 200,
                "headers": {},
                "body": JSON.stringify(data)
            };
            context.succeed(res);
        }
    });

And in my API Gateway I've created resources and methods, and pointed them to corresponding functions, but now I'm thinking to create a common lambda function with 2 methods like function putData() and function getData() and point them to appropriate methods instead of pointing to different Lambda functions. I tried to get the HTTP method by following https://kennbrodhagen.net/2015/12/02/how-to-access-http-headers-using-aws-api-gateway-and-lambda/ and then write as if(method==="GET"){...} else {...}, but unfortunately, I was unable to get the method name itself.

Please help me on how can I do this.

Thanks

1
  • if you don't need the results of the function you could use boto3 to point it to a SQS queue which has a lambda trigger. Commented Apr 20, 2019 at 19:15

2 Answers 2

1

You have to add a mapping in your API Gateway that will pass through the request method value. This could be hard coded in each end point's mapping.

The exact way to add this will depend on the structure of your current mappings.

This guide should be a helpful starting point: http://docs.aws.amazon.com/apigateway/latest/developerguide/getting-started-mappings.html

Sign up to request clarification or add additional context in comments.

Comments

1

There is no need to create custom mapping templates. In the "Integration Request" for your resource, make sure you check the "Use Lambda Proxy integration" checkbox.

Let's say your lambda function is as follows:

// NodeJS lambda function

exports.handler = function(event, context, callback) {
  // ...your application code...
};

With "Use Lambda Proxy integration" enabled, the event parameter will include http request details when your function executes. You will then have access to event.httpMethod: http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-input-format

// Sample `event` for GET request

{
  "path": "/test/hello",
  "headers": {
      "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
      "Accept-Encoding": "gzip, deflate, lzma, sdch, br",
      "Accept-Language": "en-US,en;q=0.8",
      "X-Forwarded-For": "192.168.100.1, 192.168.1.1",
      "X-Forwarded-Port": "443",
      "X-Forwarded-Proto": "https"
  },
  "pathParameters": {"proxy": "hello"},
  "requestContext": {
      "accountId": "123456789012",
      "resourceId": "us4z18",
      "stage": "test",
      "requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
      "identity": {
          "accountId": "",
          "sourceIp": "192.168.100.1",
          "userArn": "",
          "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
          "user": ""
      },
      "resourcePath": "/{proxy+}",
      "httpMethod": "GET",
      "apiId": "wt6mne2s9k"
  },
  "resource": "/{proxy+}",
  "httpMethod": "GET",
  "queryStringParameters": {"name": "me"},
  "stageVariables": {"stageVarName": "stageVarValue"}
}

NOTE: While using proxy integration, the data passed to your lambda function callback must be formatted in a specific schema, as outlined here:

http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-output-format

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "body": "..."
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.