In this section, we will create a function to list the documents stored in the DynamoDB table by user ID.
Open AWS Lambda console
Click Create function

Enter function name: list_documents

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)
}

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.

TABLE_NAME in the key field


{
"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.

