In this article, I will show you how to create and invoke two serverless AWS Lambda Functions that write and read data to and from a DynamoDB Table.
AWS offers technologies for running code, managing data, and integrating applications, all without managing servers.
Serverless technologies feature automatic scaling, built-in high availability, and a pay-for-use billing model to increase agility and optimize costs. These technologies also eliminate infrastructure management tasks like capacity provisioning and patching, so you can focus on writing code that serves your customers.
There are many AWS Serverless services and we will use some of them in that article:
AWS Lambda is a compute service that lets you run code without provisioning or managing servers.
Amazon DynamoDB is a fast and flexible nonrelational database service for all applications that need consistent, single-digit millisecond latency at any scale.
Step 1: Create DynamoDB table.
1.1 Enter the table name (planets) and primary key (id) and select String for type then click on Create Table.
1.2 Your table has been created.
1.3 Create some sample items as below from the console.
Step 2: Create First Lambda Function to insert in DynamoDB Table.
2.1 Create Lambda function with name (PutNewPlanet) and Runtime Python 3.7.
2.2 Create IAM role with DynamoDB Full Access Policy (DynamoDB-role-for-lambda-execution) to be able to insert and retrieve from DynamoDB Table.
2.3 Add your python code that we will use to insert new record in DynamoDB Table and then click on Deploy.
import json
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('planets')
def lambda_handler(event, context):
table.put_item(
Item={'id': 'Venus', 'temp': 'extremally hot'}
)
response = {
'message': 'item added'
}
print (response)
# TODO implement
return {
'statusCode': 200,
'body': response
}
2.4 Click on Test to create Test Event to trigger Lambda Function.
2.5 Click on Test to invoke lambda Function and check the output.
2.6 Go back to DynamoDB Table and Check the table items.
Step 3: Create Second Lambda Function to retrieve data from DynamoDB Table.
3.1 Create Lambda function with name (GetItemPlanet) and Runtime Python 3.7.
3.2 Add your python code that we will use to get data from DynamoDB Table and then click on Deploy.
import json
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('planets')
def lambda_handler(event, context):
response = table.get_item(
Key={'id': 'Earth'}
)
print (response)
# TODO implement
return {
'statusCode': 200,
'body': response
}
3.3 Click on Test to create Test Event to trigger Lambda Function same step as 2.4.
3.4 Click on Test to invoke lambda Function and check the output.
Here it is! You are done!
Thank you for taking the time to read my article. I hope you find it helpful.
Top comments (0)