Writing and Reading from DynamoDB using Lambda Python
...using API Gateway as trigger.
Below is a simple example of writing to and reading from a DynamoDB table. This code would be triggered by a webpage that sends a JSON package via configured API Gateway. And it would return a JSON package back to the website. Be sure the Role has the necessary permission to read and write to DynamoDB table being used.
import json
import decimal
import boto3
from boto3.dynamodb.conditions import Key, Attr
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
def lambda_handler(event, context):
# TODO implement
#define DynamoDB object
dynamodb = boto3.resource('dynamodb')
#define which table we want to use
table = dynamodb.Table("yourOwnTable")
#print the status of the table
print(table.table_status)
#Get the body string from the event input json
#we convert this to json so we can use it easier
body = json.loads(event['body'])
#we enter this into the DB
respose1 = table.put_item(
Item={
'RequestTime': body['myFormVariables']['RequestTime'],
'User': body['myFormVariables']['User'],
'entryID': body['myFormVariables']['entryID'],
'Field1': body['myFormVariables']['Field2'],
'Field2': body['myFormVariables']['Field1']
}
)
print("Table Output")
##get it all
response2 = table.scan()
##Get only the objects that match the given key
#response = table.query(KeyConditionExpression=Key('entryID').eq("L3dVGMDS7yqzdoxCxOm4fg"))
#Print all values in the response
for i in response2['Items']:
print(i['entryID'], ":", i['Field1'], ":", i['Field2'], ":", i['RequestTime'])
#Just to illustrate how I handled cognito user information that was passed in
cognito = event['requestContext']['authorizer']['claims']['cognito:username']
return {
'statusCode': 200,
'body': json.dumps(response2, cls=DecimalEncoder)
}
Test Sample
Here is a test event you can use to test your code.
{
"path": "/entry",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Authorization": "eyJraWQiOiLTzRVMWZs",
"content-type": "application/json; charset=UTF-8"
},
"queryStringParameters": null,
"pathParameters": null,
"requestContext": {
"authorizer": {
"claims": {
"cognito:username": "the_username"
}
}
},
"body": "{\"myFormVariables\":{
\"RequestTime\":"2019-01-11T05:56:22.517Z\",
\"User\":\"the_username\",
\"entryID\":\"L3dVGMDS7yqzdoxCxOm4f1\",
\"Field1\":47,
\"Field2\":122}}"
}
Output