Creating Lambda Function to Write Data

Create New Lambda Function

  1. Navigate to AWS Lambda Console
    • Select Functions from the left navigation bar
    • Click the Create function button

Create Lambda Function

  1. On the Create function page:
    • Select Author from scratch
    • Name the function: book_create
    • Choose Python 3.14 as Runtime
    • Select Architecture: x86_64
    • Click Create function

Configure Lambda Function

  1. Function created successfully

Function created

Configure Function

  1. In the book_create function interface:
    • Paste the following code into the lambda_function.py editor:
import boto3
import json

dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("Books-WS78")

def lambda_handler(event, context):
    try:
        body = event.get("body")

        # Handle both API Gateway (string) and test event (dict)
        if isinstance(body, str):
            book_item = json.loads(body)
        elif isinstance(body, dict):
            book_item = body
        else:
            raise ValueError("Invalid request body")

        table.put_item(Item=book_item)

        return {
            "statusCode": 200,
            "body": json.dumps({
                "message": "Data successfully written to DynamoDB!"
            }),
            "headers": {
                "Content-Type": "application/json"
            }
        }

    except Exception as error:
        print("Error:", str(error))
        return {
            "statusCode": 400,
            "body": json.dumps({
                "message": "Failed to write data to DynamoDB.",
                "error": str(error)
            }),
            "headers": {
                "Content-Type": "application/json"
            }
        }

Note: Change the DynamoDB table name in the code to match your DynamoDB table name.

  • Click Deploy to save changes

Configure Code

Configure IAM Permissions

  1. Add DynamoDB access permissions:
    • Select the Configuration tab
    • Select Permissions from the left menu
    • Click on the function’s role

Configure IAM

  1. On the IAM Role page:
    • Select Add permissions
    • Select Attach policies

Add permissions

  1. Find and select the AmazonDynamoDBFullAccess policy
    • Click Add permissions

Add Policy

  1. Policy attached successfully

Policy attached

Test Function

  1. Create test event:
    • Select the Test tab
    • Select Create new event

Test tab

  1. Configure test event:
  • Name the event: Test_1
  • Enter the following test JSON:
{
  "body": {
      "id": "1",
      "name": "Java Programming",
      "author": "Alex Smith",
      "category": "Technology",
      "price": "10.89",
      "description": "Hướng dẫn lập trình Java cơ bản",
      "image": "https://book-image-resize-stores-tranvix.s3.ap-southeast-1.amazonaws.com/Notification.png"
  }
}

Event JSON

  1. Click Save and Test

Save and Test

  1. Check test result - Function executed successfully

Test result

Verify Data in DynamoDB

  1. Navigate to DynamoDB Console:
  • Select Tables from the left menu
  • Select the Books table
  • Select Explore table items

View DynamoDB

  1. Verify the data has been added to the Books table

Result