Listing Lambda Function

We will create a Lambda function that reads all the data in the DynamoDB table:

  1. Open AWS Lambda console, click Create function LambdaListFunction

  2. Enter function name, e.g., books_list

    • Select Python 3.12 for Runtime
    • Click Create function LambdaListFunction
  3. Copy the following code and paste to lambda_function.py, then click Deploy

import json
import boto3
from decimal import *
from boto3.dynamodb.types import TypeDeserializer

client = boto3.client('dynamodb') 
serializer = TypeDeserializer()

class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return str(obj)
        return json.JSONEncoder.default(self, obj)
            
def deserialize(data):
    if isinstance(data, list):
        return [deserialize(v) for v in data]

    if isinstance(data, dict):
        try:
            return serializer.deserialize(data)
        except TypeError:
            return {k: deserialize(v) for k, v in data.items()}
    else:
        return data

def lambda_handler(event, context):
    data_books = client.scan(
        TableName='Books',
        IndexName='name-index'
    )
    format_data_books = deserialize(data_books["Items"])
    for book in format_data_books:
        data_comment = client.query(
            TableName="Books", 
            KeyConditionExpression="id = :id AND rv_id > :rv_id", 
            ExpressionAttributeValues={
                ":id": {"S": book['id']}, 
                ":rv_id": {"N": "0"}
            }
        )
        format_data_comment = deserialize(data_comment['Items'])
        print(data_comment['Items'])
        book["comments"] = format_data_comment
            
    print (format_data_books)
    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE, OPTIONS",
            "Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,X-Access-Token,XKey,Authorization"
        },
        "body": json.dumps(format_data_books, cls=DecimalEncoder)
    }

LambdaListFunction

  1. Next, grant the function permission to read data from DynamoDB

    • Click Configuration tab
    • Select Permissions from the left menu
    • Click on the role that the function is using LambdaListFunction
  2. On the IAM Role page, click Add permissions > Create inline policy LambdaListFunction

  3. Select JSON tab and add the following policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DynamoDBReadBooks",
      "Effect": "Allow",
      "Action": [
        "dynamodb:Scan",
        "dynamodb:Query"
      ],
      "Resource": [
        "arn:aws:dynamodb:AWS_REGION:ACCOUNT_ID:table/Books",
        "arn:aws:dynamodb:AWS_REGION:ACCOUNT_ID:table/Books/index/name-index"
      ]
    }
  ]
}
  • Replace AWS_REGION with your region (e.g., ap-southeast-1)
  • Replace ACCOUNT_ID with your AWS account ID
  • Click Next LambdaListFunction
  1. Enter policy name, e.g., LambdaBooksReadPolicy

    • Review the configured permissions
    • Click Create policy LambdaListFunction
  2. Policy created successfully and attached to role LambdaListFunction