Reputation: 9
I am new in AWS trying to learn, how to make a REST API(Non-Proxy Integration) with Lambda function and Dynamo DB. I have enabled the cors, configured the Method Request and Method Response of REST API in resources. My Lambda function code seems to be correct, but when I call this API from POSTMAN or react application it returns NULL.
LAMBDA FUNCTION:-
var AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient({region : 'us-west-2'});
exports.handler = async (event) => {
if(event.httpMethod==='GET')
{
console.log("GET method if is called")
return readDatabase(event);
}
};
function readDatabase(event)
{
try{
console.log("inside readDatabase function")
let params = {
TableName: 'devicedata',
};
return ddb.scan(params).promise()
.then(data=>{
const response ={
statusCode: 200,
body : JSON.stringify({
"deviceData" : data
})
}
return response;
});
}
catch (e) {
let response = {
statusCode: 400,
body: JSON.stringify({
"Message": "Error in Read From Database function",
"Details": e
})
}
return response;
}
}
REST API RESOURCES:-
Integration Response Header Mapping :-
Method Reponse Configuration:-
These are the configurations, but it sends output as - "null".
Trigger in MY Lambd Function:-
Upvotes: 0
Views: 2440
Reputation: 765
I had something similar to this and my solution ended up being that in my lambda function I needed to specify exactly the httpMethod being used and the response generated, so you might notice that in your event, the httpMethod is "OPTIONS" where instead you may mean for it to be "POST" or "PUT", to handle this prior to invoking my lambda function in the event.handler, I made an optional condition like so;
if(event.requestContext.httpMethod === 'OPTIONS'){
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "*",
"Content-Type": "*/*",
"Accept": "*/*"
},
}
return response
}
let functionResponse = await function(arg2, arg1);
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "*",
"Content-Type": "*/*",
"Accept": "*/*"
},
body: JSON.stringify(functionResponse),
};
return response;
};
Upvotes: 0
Reputation: 231
First of all, you have to check your lambda function if it works correctly: you can use the predefined tests from lambda looking like this:
then if lambda works and it still returns NULL try to check the integration request and response settings just before and after lambda function.
Upvotes: 3