Deploy an AWS Lambda to retrieve a record from DynamoDB with the Serverless Framework

Nik Graf
InstructorNik Graf
Share this video with your friends

Social Share Links

Send Tweet

To retrieve a previously created item from a DynamoDB table we have to setup the IAM permissions for the Lambda to get an item and further implement the code using the DynamoDB DocumentClient API.

Instructor: [00:00] To retrieve an item from the DynamoDB table, we create a new function, getTodo, and we attach an HTTP event. This time, our path actually should include a path parameter. Using curly braces, we can make it happen.

[00:16] The event object then passed to the function will include this parameter, d. Next up, we also need to give the function permissions to actually retrieve an item from DynamoDB. Therefore, we add DynamoDB getItem.

[00:30] Be aware that with this configuration, every function we deploy in this stack will have the same permissions. To lock them down, you need to create custom confirmation EM permissions. Since this isn't that convenient in serverless.yml, we're going to skip it for now.

[00:47] Our configuration is complete, and we can move on to the code part. We create the file, get JS, and fill in our function.

[01:13] As previously mentioned, we can access the key ID and get it from the path parameters inside the event. Then we get the result. In case we found an item, we're going to return a response with the status code 200. In case no item was found, we return a 404 with an error message.

[01:36] Everything is in place, and we can redeploy with our new function.

[01:41] Once the deploy was successful, we can retrieve the to-do we previously created.

[02:19] In the case we provide an ID from an entry that doesn't exist, we get a 404, as expected. Keep in mind, as an alternative, we can still invoke the function using SLS invoke. This comes in especially handy in case you added logging statements for debugging.