Retrieve DynamoDB data Item using Lambda — AWS

This article shows you how to work read data stored in DynamoDB using a lambda function.

While creating a Lambda function make sure you assign the IAM Role for Lambda, which has the Policy of “AWSLambdaFullAccess” attached to it. Make sure the other required policies have been attached, like AWSLambdaExcute and AmazonDynamoDBFullAccess since we are working with DynamoDB.

In your database key values are important as you will use the same for scanning the database. Now for this example, I have created a fake DB with ID as my Primary partition key.

A snippet of my DynamoDB is given below. You need to add data into the table to retrieve something by your lambda function otherwise, the output will be null. Here I have inserted dummy data. Currently, this is done manually because it's test data, but we can also do it using a .csv file or other methods which will be covered in another article.

Image: AWS DynamoDB testTable preview

Tip: make sure your table and lambda function is in the same AWS region.

Once you have your data in dynamoDB setup, we need to write our lambda function. So go to Services->Lambda->Create Function. Here give in a unique name restricted to your account and choose runtime language as Node.js 14.x since that's the one we’re using here.

Don't forget to add an IAM role and attach AWSLambdaFullAccess and AmazonDynamoDBFullAccess policy to it. These policies help interact your lambda with your dynamoDB.

Here is the reference image for the policies attached.

Image: AWS IAM Role

Now once all this is done, you can finally write code in your lambda function. Since this is a learning environment your doing all of this by yourself. In a real-time scenario, the data and the role will already be present, you’ll just have to integrate them into your Lambda function.

Image: AWS-Lambda Function

Now, in the lambda function, go to the index.js file and import ‘aws-sdk’ and create a new object of new AWS.DynamoDB(). Next in our exports.handler function, we define our params variable by giving in all the required details such as our Key and TableName. Once this is done we use the ‘getItem’ function to get the required item, from our table.

This is using only one variable, we can query multiple variables as well and get the data accordingly.

Next, Make sure you create a test event as well. The following shows the test event code to get the required item. Now whichever Id is given in the test event, only those details will be retrieved.

Image: AWS-Lambda_testEvent

The output is given below, this is in JSON format, can be seen in the execution results window.

Image: Final Output

Writer | Developer | Travelhead

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store