top of page
検索

Get data from DynamoDB using Boto3 with aws lambda Python

  • robin05156
  • 2023年7月6日
  • 読了時間: 1分

Let's retrieve data from 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
from boto3.dynamodb.conditions import Key, Attr

def lambda_handler(event, context):
    print(event)
    table_name = 'testdb'
    
    dynamo = boto3.resource('dynamodb')
    table = dynamo.Table(table_name)
    response = table.query(KeyConditionExpression=Key('Artist').eq(event['artist']))
    
    return(response)

Call the boto3 module with import.

Then define the table name to use.

Using boto3 to get the dynamodb object

Get value from DB using query. This time, we set the condition to get the data that the value obtained from payload matches the key of Artist in DB.

End by returning the last added result.


Test payload

{
    "artist": "Michael Jackson"
}

Execution result


{
	"Items": [
		{
			"Title": "Thriller",
			"Artist": "Michael Jackson"
		}
	],
	"Count": 1,
	"ScannedCount": 1,
	"ResponseMetadata": {
		"RequestId": "***************",
		"HTTPStatusCode": 200,
		"HTTPHeaders": {
			"server": "Server",
			"date": "Wed, 07 Jun 2023 09:03:16 GMT",
			"content-type": "application/x-amz-json-1.0",
			"content-length": "98",
			"connection": "keep-alive",
			"x-amzn-requestid": "***************",
			"x-amz-crc32": "4290830663"
		},
		"RetryAttempts": 0
	}
}

I was able to get a value that matched the conditions when I executed it.



 
 
 

© Copyright ROBIN planning LLC.

bottom of page