Write data by Lambda function

In this step, we create Lambda function to write data to created DynamoDB table.

  1. Open AWS Lambda console LambdaConsole
  2. Click Create function CreateFunction
  3. Enter function name: book_create
  • Select Python 3.9 for Runtime
  • Click Create function CreateFunction
  1. 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
  • Click Deploy AttachPolicies
  1. 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 AttachPolicies
  • Click Attach permissions
  • Select Attach policies AttachPolicies
  • Enter dynamoDB to search policy.
  • Check to policy: AmazonDynamoDBFullAccess
  • Click Attach policies AttachPolicies
  1. Create a event to test function operation
  • Click to tab Test
  • Enter event name, such as: test_1
  • Enter the below data into Event JSON
{
  "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.ap-southeast-2.amazonaws.com/Java.jpg"
  }
}
  • Click Save
  • Click Test CreateTestEvent
  1. Navigate to DynamoDB console
  • Click Update settings on the left menu
  • Check to Books
  • Click Explore table items CheckTable
  1. You will get all the data from the table. CheckTable