Create listing function

In this section, we will create a function to list the documents stored in the DynamoDB table by user ID.

  1. Open AWS Lambda console

  2. Click Create function LambdaConsole

  3. Enter function name: list_documents

  • Select Python 3.14 for Runtime
  • Click Create function

CreateFunction

  1. Enter the following code for the lambda_function.py file:
import json
import boto3
import os
from decimal import *
from boto3.dynamodb.types import TypeDeserializer

dynamodb = 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):
    table_name = os.environ['TABLE_NAME']
    user_id = event['pathParameters']['id']
    print(user_id)
    docs = dynamodb.query(
        TableName=table_name,
        KeyConditionExpression="user_id = :id",
        ExpressionAttributeValues={ ":id": { 'S': user_id } }
    )
    
    format_data_docs = deserialize(docs["Items"])
    # TODO implement
    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_docs, cls=DecimalEncoder)
    }
  • Then click Deploy

CreateFunction

The above code gets the TABLE_NAME environment variable and the user’s ID. It then queries the DynamoDB table with the condition that the Partition key equals the user’s ID, and reformats the returned data.

  1. We need to add an environment variable to the function. Click the Configuration tab, then select Environment variables in the left menu. Click Edit

EnvironmentVariables

  1. Click Add environment variable
  • Enter TABLE_NAME in the key field
  • Enter the name of the DynamoDB table you just created in the value field
  • Click Save

EnvironmentVariables

  1. Next, add permissions for the function to access the DynamoDB table
  • Click Permissions in the left menu
  • Click the function’s execution role

Permission

  1. Expand the AWSLambdaBasicExecutionRole… policy, then click Edit

Permission

  1. Copy the JSON below into the JSON editor
        {
            "Effect": "Allow",
            "Action": [
                "dynamodb:Query"
            ],
            "Resource": "arn:aws:dynamodb:REGION:ACCOUNT_ID:table/Documents"
        }

Replace REGION and ACCOUNT_ID with the region where you created the table and your account ID.

  • Click Next

Permission

  1. Click Save changes

Permission