AWS: Delete DynamoDB Data With Lambda
Intro
In the recent posts we have been creating a serverless application with API Gateway, Lambda and DynamoDB. We have covered the process of adding and retrieving items from the database. Now let us quickly sum everything up with a review showing how to delete an item.
First let us start with the request, which is going to get routed through API Gateway. A deletion request would take the following format
DELETE:api-url/compare-yourself/?userid=XXXXXX
Where the http request type is DELETE, and the userid at the end is a variable parameter that defines which users data we are deleting. We use the user ID here because that is unique key that we have chosen for items in our DynamoDB table.
Let's start with API Gateway.
API Gateway
We start by making a new DELETE method on the root resource compare-yourself.
Then inside of integration request we choose Lambda Function as the integration type. Our lambda function is called cyDeleteData
.
And then lastly in the integration request we need to map the userid
parameter from the request URL into our JSON object that we are forwarding to Lambda.
{
"userid" : "$input.params('userid')"
}
If we are confused about the syntax of this mapping template please review these resources:
📘 AWS Docs: Setting up data transformations for REST APIs
📘 velocity.apache.org : User Guide
And at this point we are forwarding the userid in a JSON object to the Lambda function cyDeleteData. Let's go there and review our function.
Lambda
The purpose of this function is to contact the DynamoDB service with a delete request, which must include information on which table to look for the user, and the userid of the user to delete. Note that we are choosing not to use the document handler in this instance and are calling DynamoDB directly.
// Import the AWS SDK
var AWS = require("aws-sdk");
var dynamodb = new AWS.DynamoDB({
region: "us-east-2",
apiVersion: "2012-08-10",
});
// Handler
exports.handler = (event, context, callback) => {
// extract User ID
const userid = event.userid;
var params = {
TableName: "compare-yourself",
Key: {
"UserId": {
S: `${userid}`
}
},
ConditionExpression: 'attribute_exists(UserId)' // highlight-line
};
dynamodb.deleteItem(params, function(err, data) {
// error
if (err) {
console.log(err);
callback(err);
}
// successful delete
else {
console.log(`Data for user ${userid} successfully deleted`);
console.log(data);
callback(null, `Data for user ${event.userid} successfully deleted`);
}
});
}
I've highlighted the ConditionExpression
parameter above, which I think is very useful. This parameter checks to make sure that the table actually contains a matching user ID before executing the delete function. If we don't include this we will get a successful deletion callback, even if there is no item to delete. Which in my view is a mistake. If the user we are trying to delete doesn't exist we need to be aware of that.
Integration Response
Back in API Gateway, would could do some sort of mapping in our Integration Response if we really wanted to, but we are going to leave that section completely blank. We really just need confirmation one way or the other that this deletion worked, we aren't getting back a big chunk of data that needs to be formatted.
Wrapping Up
Make sure that you have actually deployed your API Gateway changes, otherwise you will get an error and the request won't even make it to Lambda.
Testing
Let's test this live on the internet with Postman. Here is a quick screencap of whats in the database right now.
Let's delete user003.
And the test is successful.
Comments
Recent Work
Basalt
basalt.softwareFree desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.
BidBear
bidbear.ioBidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.