In this step, we create Lambda function to write data to created DynamoDB table.
Open AWS Lambda console, then Click Create function
Enter function name: book_create
Copy the below code into tab lambda_function
import boto3
import json
client = boto3.resource('dynamodb')
def lambda_handler(event, context):
book_item = event["body"]
error = None
try:
table = client.Table('Books')
table.put_item(Item = book_item)
except Exception as e:
error = e
if error is None:
response = {
'statusCode': 200,
'body': 'writing to dynamoDB successfully!',
'headers': {
'Content-Type': 'application/json'
},
}
else:
response = {
'statusCode': 400,
'body': 'writing to dynamoDB fail!',
'headers': {
'Content-Type': 'application/json'
},
}
return response
Next, add additional permissions for Lambda access to DynamoDB
Click to tab Configure
Click Permissions on the left menu
Click to role the function executing
Click Attach permissions
Select Attach policies
Enter dynamoDB to search policy.
Check to policy: AmazonDynamoDBFullAccess
Click Add permision
Create a event to test function operation
{
"body": {
"id": "1",
"name": "Java",
"author": "Alex",
"category": "IT",
"price": "10.89",
"description": "This book guide to create Java web basic",
"image": "https://book-image-resize-store.s3.us-east-1.amazonaws.com/Java.jpg"
}
}
Navigate to DynamoDB Tables console
Click Explore table items
You will get all the data from the table.