Write data by Lambda function

Creating the Lambda Function

  1. Navigate to the AWS Lambda Console

    • Select Functions from the left navigation
    • Click Create function Lambda Console Navigation
  2. Configure the Function Settings:

    • Select Author from scratch
    • Function name: book_create
    • Runtime: Python 3.11
    • Click Create function Lambda Function Creation
  3. Implement the Function Code:

    • In the Code tab, replace the contents with:
    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 to save your changes Lambda Function Code

Configuring Permissions

  1. Set up DynamoDB Access:

    • Navigate to the Configuration tab
    • Select Permissions from the left sidebar
    • Click the execution role link Lambda Permissions
  2. Add DynamoDB Policy:

    • Click Attach permissions
    • Select Attach policies Add Policy
    • Search for and select AmazonDynamoDBFullAccess
    • Click Add permission DynamoDB Policy

Testing the Function

  1. Create a Test Event:

    • Go to the Test tab
    • Create a new test event named test_1
    • Use this sample 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.us-east-1.amazonaws.com/Java.jpg"
      }
    }
    
    • Click Save, then Test Test Configuration

Verifying Data in DynamoDB

  1. Access Your DynamoDB Table:

    • Open the DynamoDB console
    • Select the Books table
    • Click Actions > Update settings DynamoDB Table Access
  2. View Table Items:

    • Select Explore table items Explore Items
  3. Review the Data:

    • Verify your test data appears in the table Table Data