Reputation: 2456
I'm trying to write a Lambda function that uses the request-promise library to make an external https request. This is what I have:
exports.handler = async (event, context, callback) => {
console.log("Starting call: " + event.queryStringParameters.filter);
console.log("Decoded param: " + decodeURIComponent(event.queryStringParameters.filter));
var filter = JSON.parse(decodeURIComponent(event.queryStringParameters.filter));
console.log("Filter: " + filter);
var ingredients = filter.ingredients;
var options = {
uri: 'https://api.*****.com/search',
qs: {
app_id: '****',
app_key: '*****',
q: ingredients.join(' ')
},
json: true
};
console.log("Done calling stuff");
rp(options)
.then(function(recipes) {
console.log('Response: ' + recipes);
var recipesToReturn = [];
recipes.hits.forEach(function(recipeHit) {
recipesToReturn.push(objectMapper(recipeHit.recipe, recipeMap));
});
console.log('Recipes:', recipesToReturn);
const response = {
statusCode: 200,
body: JSON.stringify(recipesToReturn),
};
return JSON.stringify(response);
})
.catch(function(err) {
console.log('Error:', err)
const response = {
statusCode: 400,
body: err,
};
return JSON.stringify(response);
});
};
When I test out the API Gateway request, I see this:
Sun May 26 16:59:21 UTC 2019 : Execution failed due to configuration error: Malformed Lambda proxy response
I've been trying to read up on how the Lambda Proxy Responses should be formatted, and I'm assuming that I'm missing something with regards to the callback or the context, but I have not been able to figure out how to make it work with the request-promise library.
Upvotes: 1
Views: 2027
Reputation: 971
In proxy integration API Gateway simply passes entire request and response between frontend and the backend.
It is the problem with the response lambda function sent to the API Gateway.
Response to the lambda should have the following key-values
{
"isBase64Encoded": true|false,
"statusCode": httpStatusCode,
"headers": { "headerName": "headerValue", ... },
"body": "..."
}
isBase64Encoded : If you are not working with binary data set it to false.
statusCode : Is the HTTP response that is interpreted by API Gateway.
body : if you are sending JSON it must be converted to a string. In node.js you can use JSON.stringify() method.
The following could be the proper response to API Gateway
const response = {
statusCode: 200,
isBase64Encoded: false
headers:""
body: JSON.stringify(recipesToReturn),
};
Upvotes: 1