In this task, we’ll create the final Lambda function that provides a method for retrieving information about posts from our DynamoDB database. This function plays a crucial role in our serverless blog-to-audio system by enabling efficient data retrieval.
PostReader_GetPostReplace the existing code in the Lambda function with the following:
import boto3
import os
from boto3.dynamodb.conditions import Key, Attr
def lambda_handler(event, context):
postId = event["postId"]
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['DB_TABLE_NAME'])
if postId=="*":
items = table.scan()
else:
items = table.query(
KeyConditionExpression=Key('id').eq(postId)
)
return items["Items"]
This function is very short. It expects to get the post ID (the DynamoDB item ID) and, based on this ID, it retrieves all information (including the S3 link to the audio file if it exists) and then returns it. To make it a little more user-friendly, if the input parameter is an asterisk (*), the Lambda function returns all items from the database. For a database with a lot of items, avoid this approach because it can degrade performance and might take a long time.
Choose Deploy.
You need to provide the name of the DynamoDB table as an environment variable for the function.
DB_TABLE_NAMEpostsAllPosts{
"postId": "*"
}
You should see the message: Execution result: succeeded.
If you expand the Details section, you should see a list of all records from the DynamoDB table.
You can now proceed to the next task.