top of page

Add new item to DynamoDB using Boto3 in aws lambda Python

  • ろびん
  • 2023年7月6日
  • 読了時間: 1分

Let's add an item to DynamoDB using Python and Boto3.

The environment I used this time

DynamoDB: Create a table called "testdb" in advance

Runtime : python3.10 (run with lambda)


Python code

import json
import boto3

def lambda_handler(event, context):
    print(event)
    table_name = 'testdb'
    item = {
       'Artist': event['artist'],
       'Title': event['title']
    }
    dynamo = boto3.resource('dynamodb')
    table = dynamo.Table(table_name)
    response = table.put_item(Item=item)
    
    print(response)

Call the boto3 module with import.

After that, define the table name to use and get the item to be added to the DB from the payload (event argument).

Using boto3 to get the dynamodb object

Use put_item to add items to DB.

Print the last added result.


Test payload

{
    "artist": "Michael Jackson",
    "title": "Thriller"
}

Execution result

START RequestId: ******************************** Version: $LATEST
{'artist': 'Michael Jackson', 'title': 'Thriller'}
{'ResponseMetadata': {'RequestId': '*********************', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'Server', 'date': 'Wed, 07 Jun 2023 05:26:26 GMT', 'content-type': 'application/x-amz-json-1.0', 'content-length': '2', 'connection': 'keep-alive', 'x-amzn-requestid': '***************************', 'x-amz-crc32': '2745614147'}, 'RetryAttempts': 0}}
END RequestId: ************************
REPORT RequestId: ****************************	Duration: 1625.71 ms	Billed Duration: 1626 ms	Memory Size: 128 MB	Max Memory Used: 70 MB	Init Duration: 253.35 ms

When executed, "ResponseMetadata" is output.


Check DB

ree

When you access "DynamoDB" from the aws console screen, select testdb from "Search items", and check "Returned items", the items added from lambda python using Boto3 are displayed. You can confirm that

 
 
 

© Copyright ROBIN planning LLC.

bottom of page