tell me the best way to build an api gateway lambdanodejs and dynamodb using sam cli?

The event object that will come from the API gateway invocation will have the following structure –

{
  resource: '/func1',
  path: '/func1',
  httpMethod: 'POST',
  headers: {
    accept: '*/*',
    'content-type': 'application/x-www-form-urlencoded',
    Host: '0000000000.execute-api.ap-south-1.amazonaws.com',
    'User-Agent': 'curl/7.71.1',
    'X-Amzn-Trace-Id': 'Root=1-5fa018aa-60kdfkjsddd5f6c6c07a2',
    'X-Forwarded-For': '178.287.187.178',
    'X-Forwarded-Port': '443',
    'X-Forwarded-Proto': 'https'
  },
  multiValueHeaders: {
    accept: [ '*/*' ],
    'content-type': [ 'application/x-www-form-urlencoded' ],
    Host: [ '0000000000.execute-api.ap-south-1.amazonaws.com' ],
    'User-Agent': [ 'curl/7.71.1' ],
    'X-Amzn-Trace-Id': [ 'Root=1-5fa018aa-603d90fhgdhdgdjhj6c6dfda2' ],
    'X-Forwarded-For': [ '178.287.187.178' ],
    'X-Forwarded-Port': [ '443' ],
    'X-Forwarded-Proto': [ 'https' ]
  },
  queryStringParameters: null,
  multiValueQueryStringParameters: null,
  pathParameters: null,
  stageVariables: null,
  requestContext: {
    resourceId: 'scsu6k',
    resourcePath: '/func1',
    httpMethod: 'POST',
    extendedRequestId: 'VYjfdkjkjfjkfuA=',
    requestTime: '02/Nov/2020:14:33:14 +0000',
    path: '/test/func1',
    accountId: '00000000000',
    protocol: 'HTTP/1.1',
    stage: 'test',
    domainPrefix: 'f8h785q05a',
    requestTimeEpoch: 1604327594697,
    requestId: '459e0256-9c6f-4a24-bcf2-05520d6bc58a',
    identity: {
      cognitoIdentityPoolId: null,
      accountId: null,
      cognitoIdentityId: null,
      caller: null,
      sourceIp: '178.287.187.178',
      principalOrgId: null,
      accessKey: null,
      cognitoAuthenticationType: null,
      cognitoAuthenticationProvider: null,
      userArn: null,
      userAgent: 'curl/7.71.1',
      user: null
    },
    domainName: '000000000.execute-api.ap-south-1.amazonaws.com',
    apiId: 'lkjfslkfj'
  },
  body: '{"id":"1","name":"John"}',
  isBase64Encoded: false
}

From the above event which is JSON object, we need the body. Since, the body is a string, so we need to convert it into JSON object.

So, write.js should be modified to –

var AWS = require('aws-sdk');
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = async (event) => {
    try {
        
            //console.log(event);
            //console.log(event.body);
            var obj = JSON.parse(event.body);
        
            //console.log(obj.id);
            //console.log(obj.name);
        
            var ID = obj.id;
            var NAME = obj.name;
        
        
            var params = {
                TableName:'tabmine',
                Item: {
                 id : {S: ID}, 
                 name : {S: NAME}
                }
            
            };
        
            var data;
            var msg;
            
            try{
                data = await ddb.putItem(params).promise();
                console.log("Item entered successfully:", data);
                msg = 'Item entered successfully';
            } catch(err){
                console.log("Error: ", err);
                msg = err;
            }
        
        
            var response = {
                'statusCode': 200,
                'body': JSON.stringify({
                    message: msg
            })
        };
    } catch (err) {
        console.log(err);
        return err;
    }

    return response;
};

Similarly, read.js will get modified to –

var AWS = require('aws-sdk');
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = async (event) => {
    try {
        
            //console.log(event);
            //console.log(event.body);
            var obj = JSON.parse(event.body);
        
            //console.log(obj.id);
            //console.log(obj.name);
        
            var ID = obj.id;
        
        
            var params = {
                TableName:'tabmine',
                Key: {
                 id : {S: ID}
                }
            
            };
        
            var data;
            
            try{
                data = await ddb.getItem(params).promise();
                console.log("Item read successfully:", data);
            } catch(err){
                console.log("Error: ", err);
                data = err;
            }
        
        
            var response = {
                'statusCode': 200,
                'body': JSON.stringify({
                    message: data
            })
        };
    } catch (err) {
        console.log(err);
        return err;
    }

    return response;
};

So, this will solve the problem. And template.yaml file is also correct.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top