0
0
DynamodbHow-ToBeginner · 4 min read

How to Use DynamoDB with Lambda: Simple Guide

To use DynamoDB with AWS Lambda, you write Lambda functions that use the AWS SDK to access DynamoDB tables. Inside your Lambda code, you create a DynamoDB client, then call methods like getItem or putItem to read or write data.
📐

Syntax

Using DynamoDB in Lambda involves these parts:

  • Import AWS SDK: Load the AWS SDK to access DynamoDB.
  • Create DynamoDB client: Initialize a DynamoDB DocumentClient to work with JSON data easily.
  • Call DynamoDB methods: Use methods like get, put, update, or delete to interact with your table.
  • Handle responses: Process the data returned or errors inside your Lambda function.
javascript
const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event) => {
  const params = {
    TableName: 'YourTableName',
    Key: { id: event.id }
  };

  try {
    const data = await dynamoDb.get(params).promise();
    return data.Item;
  } catch (error) {
    throw new Error('Error fetching data');
  }
};
💻

Example

This example Lambda function reads an item from a DynamoDB table named Users using an id passed in the event. It returns the user data if found.

javascript
const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event) => {
  const params = {
    TableName: 'Users',
    Key: { id: event.id }
  };

  try {
    const data = await dynamoDb.get(params).promise();
    if (!data.Item) {
      return { statusCode: 404, body: 'User not found' };
    }
    return { statusCode: 200, body: JSON.stringify(data.Item) };
  } catch (error) {
    return { statusCode: 500, body: 'Error reading user' };
  }
};
Output
{"statusCode":200,"body":"{\"id\":\"123\",\"name\":\"Alice\"}"}
⚠️

Common Pitfalls

Common mistakes when using DynamoDB with Lambda include:

  • Not setting correct IAM permissions for Lambda to access DynamoDB.
  • Using the low-level DynamoDB client instead of DocumentClient, which requires manual data marshalling.
  • Forgetting to await asynchronous calls, causing unexpected behavior.
  • Not handling errors properly, which can cause Lambda to fail silently.
javascript
/* Wrong: Missing await causes promise to be returned instead of data */
const data = dynamoDb.get(params).promise();

/* Right: Await the promise to get data */
const data = await dynamoDb.get(params).promise();
📊

Quick Reference

StepDescriptionExample Code Snippet
1Import AWS SDK and create DynamoDB clientconst AWS = require('aws-sdk'); const dynamoDb = new AWS.DynamoDB.DocumentClient();
2Define parameters for your operationconst params = { TableName: 'Table', Key: { id: '123' } };
3Call DynamoDB method with awaitconst data = await dynamoDb.get(params).promise();
4Handle success or errortry { ... } catch (error) { ... }

Key Takeaways

Use AWS SDK's DynamoDB DocumentClient inside Lambda for easy JSON data handling.
Always await asynchronous DynamoDB calls to get correct results.
Ensure Lambda has proper IAM permissions to access your DynamoDB table.
Handle errors in Lambda to avoid silent failures.
Test your Lambda function with sample events to verify DynamoDB integration.