Write data by Lambda function

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

  1. Open AWS Lambda console, then Click Create function LambdaConsole

  2. Enter function name: book_create

    • Select Python 3.9 for Runtime
    • Click Create function LambdaConsole
  3. 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 LambdaConsole
  4. 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 LambdaConsole

    • Click Attach permissions

    • Select Attach policies LambdaConsole

    • Enter dynamoDB to search policy.

    • Check to policy: AmazonDynamoDBFullAccess

    • Click Add permision LambdaConsole

  5. 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.us-east-1.amazonaws.com/Java.jpg"
      }
      }
      
    • Click Save
    • Click Test LambdaConsole
  6. Navigate to DynamoDB Tables console

    • Choose Books Tables
    • Then click Actions then Update settings LambdaConsole
  7. Click Explore table items LambdaConsole

  8. You will get all the data from the table. LambdaConsole