Software Engineering

How to Create a DynamoDB Table and Add Items to it using Python 3 from Lambda


To create a DynamoDB table and add items to it using Python 3 from AWS Lambda, you can use the AWS SDK for Python, also known as Boto3. Here’s a step-by-step guide:

  1. Set up your AWS environment:
    • Install Boto3 by running pip install boto3 in your local development environment.
    • Set up your AWS credentials and configure your AWS CLI or environment variables. You can find detailed instructions in the AWS documentation.
  2. Create a Lambda function in the AWS Management Console:
    • Go to the AWS Management Console and navigate to the Lambda service.
    • Click on “Create function” and follow the instructions to create a new Lambda function.
    • Choose the desired runtime as Python 3.x.
  3. Write the Python code to create the DynamoDB table and add items:
    • In the Lambda function code editor, enter the following code:
import boto3

def lambda_handler(event, context):
    # Create a DynamoDB client
    dynamodb = boto3.client('dynamodb')

    # Define the table name and schema
    table_name = 'YourTableName'
    table_schema = [
        {
            'AttributeName': 'ID',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'Name',
            'AttributeType': 'S'
        }
    ]

    # Create the DynamoDB table
    dynamodb.create_table(
        TableName=table_name,
        KeySchema=[
            {
                'AttributeName': 'ID',
                'KeyType': 'HASH'
            }
        ],
        AttributeDefinitions=table_schema,
        ProvisionedThroughput={
            'ReadCapacityUnits': 5,
            'WriteCapacityUnits': 5
        }
    )

    # Wait for the table to be created
    dynamodb.get_waiter('table_exists').wait(TableName=table_name)

    # Add items to the table
    items = [
        {
            'ID': {'N': '1'},
            'Name': {'S': 'Item 1'}
        },
        {
            'ID': {'N': '2'},
            'Name': {'S': 'Item 2'}
        }
    ]

    with dynamodb.batch_writer(TableName=table_name) as batch:
        for item in items:
            batch.put_item(Item=item)

    return {
        'statusCode': 200,
        'body': 'DynamoDB table created and items added successfully.'
    }
  1. Configure the Lambda function:
    • In the AWS Lambda function configuration, specify the following:
      • Handler: Enter the name of the Python file and the lambda_handler function. For example, filename.lambda_handler.
      • Runtime: Python 3.x.
      • Timeout: Set an appropriate timeout based on the expected execution time of your code.
      • Role: Choose or create an execution role with appropriate DynamoDB permissions.
  2. Save and test the Lambda function:
    • Save the Lambda function by clicking on the “Save” button.
    • Test the function by clicking on the “Test” button and configuring a test event.
    • Monitor the execution logs and check for any errors or exceptions.

When you invoke the Lambda function, it will create a DynamoDB table with the specified schema and add the items to it using a batch write operation. Make sure to replace 'YourTableName' with the desired name for your DynamoDB table.

Ensure that the IAM role assigned to the Lambda function has the necessary permissions to create and write to DynamoDB tables.