Blog 0.5: API Gateways with AWS Lambda to store on DynamoDB
Storing files from API Gateway to DynamoDB
We can use Lambda to run our function which can get files from specified API gateways and store into the DynamoDB. With Lambda we can process records in AWS DynamoDB. Furthermore, we can use DynamoDB Streams, we can trigger a Lambda function to perform additonal work each time a DynamoDB is updated.
AWS LAMBDA
AWS Lambda is a compute service that lets you run code without provisioning or managing servers. Lambda runs your code only ywhen needed and scales automatically, from a few requests per day to thousands per second. You only pay for the compute time what you consume.
We can also use Lambda to run your code in response to events, such as changes to data in an Amazon Simple Storage Service (Amazon S3) bucket or an Amazon DynamoDB table; to run your code in response to HTTP requests using Amazon API Gateway; or to invoke your code using API calls made using AWS SDKs.
Steps:
- Navigate the Lambda service in console
- Create a function
- Select the Runtime: Python: 3.8
- Use Exisitng Role: We need to create a new ROLE with policies that gives permissions to interact with specified Services
IAM ROLE
An IAM role is an IAM identity that you can create in your account that has specific permissions. An IAM role is similar to an IAM user, in that it is an AWS identity with permission policies that determine what the identity can and cannot do in AWS.
For this paritcular function with LAMBDA, we need to attach the following Permissions with the role.
- AmazonDynamoDBFullAccess
- AmazonS3ReadOnlyAccess
- CWLogsPolicy (inline policy)- This policy will basically allows LOGS to create Log Groups, CreateLogStream, and PutLogEvents
NOTE: AWS Cloudwatch Logs allows to view all the LOGS which is often used for Debugging Lambda functions.
AWS Lambda Function:
We can either paste the code or we can even upload the code using the zip folder with the code. I will post more about the code that handles AWS Lambda function on my next upcoming blogs.
Below is an exmample of AWS Lambda Handler that returns the response code:
exports.handler = async (event) => {
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
Add Trigger
We can add Trigger function that can trigger the particular Lambda function. We can use different AWS service on the selection based on event type. Selecting the Event Type allows to trigger the function based on different criteria.
- Select the S3 Bucket
- Event Type: all object create events. This event type determines the LAMBDA function to run whenever an OBJECT is created in the S3 Bucket.
NOTE: Writing to the SAME bucket can increase the risk of creating recurssive invocation (increasing usage and costs).