I’m trying to use Lambda functions for a basic database API, with calls to be made directly to each Lambda function via its function URL.
It’s working perfectly for getting a database item by its id, but when I try to use put instead, the item isn’t added to the table.
I’ve tried multiple different methods and examples, but haven’t been able to get any of them working. With some examples from AWS documentation and other guides/threads, I had various 502 errors and issues with node version, import vs. require etc.
With others, the function runs fine without errors but the item simply isn’t added to the DynamoDB table. The execution role of the Lambda function has DynamoDBFullAccess (in fact, I gave it all policies with DynamoDB in the name).
I would really appreciate a solution that isn’t just a code snippet, but includes information on setting up the function, e.g. which node version the code is for, and the complete code including imports and exports.
The working Lambda function for getting an item by id:
const AWS = require ('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient({
region: 'us-east-1'
});
exports.handler = async (event) => {
const id = +event.queryStringParameters.id
const params = {
TableName: "test",
Key: {
"id": id
}
};
const data = await dynamoDb.get(params).promise();
const response = {}
if ((typeof data) === "object") {
response.statusCode = 200;
response.body = JSON.stringify(data);
} else {
response.statusCode = 500;
}
return response;
};
An attempt using put. This returns an empty object with a 200 status code, as expected, but the hardcoded item is not added to the table ‘test’. No errors in CloudWatch at all.
const AWS = require ('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient({
region: 'us-east-1'
});
exports.handler = async (event) => {
const params = {
TableName: "test",
Item: {
"id": 1
}
};
const data = await dynamoDb.put(params).promise();
const response = {}
if ((typeof data) === "object") {
response.statusCode = 200;
response.body = JSON.stringify(data);
} else {
response.statusCode = 500;
}
return response;
};
2
Answers
Turns out my problem was simple user error, as usual! I was checking the table's item count to see if the item had been posted, without realising the item count takes 6 hours to update. The items had in fact been posting after all!
You should always wrap async methods in try/catch blocks to expose any exceptions.
Regardless, it looks like your GetItem uses a String as
id
whereas your PutItem uses a number.Ensure you are using the correct data type and add the try/catch and your issue should be sorted.