Using AWS Lambda with Amazon API Gateway – Malformed Lambda proxy response
The Error
Execution failed due to configuration error: Malformed Lambda proxy response
Wed Oct 26 01:35:28 UTC 2016 : Method completed with status: 502
The Fix
There’s a bunch of stuff you need to check to fix this error.
First, on your routes in Amazon API gateway, make sure you are using LAMDA_PROXY as your Integration Request.
Make sure “Use lambda proxy integration” is checked.
Finally, check your node code for the correct callback object and the correct callback function (you should not be using callback, you should be using context.succeed).
"use strict";
process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'];
var handler = function(event, context, callback){
const query = event.queryStringParameters || {};
const eventParams = event.body ? JSON.parse(event.body) : {};
var data = {
results: [1,2,3],
success: true
};
// here's the object we need to return
const res = {
"statusCode": 200,
"headers": {},
"body": JSON.stringify(data) // body must be returned as a string
};
context.succeed(res); // we must use this callback to return to amazon api gateway
//callback(null, JSON.stringify(res, null, 2)); // this does not work with the api
};
exports.handler = handler;
The Amazon API Gateway callback object is at the very bottom of this page. The documentation sucks, but it’s there.
https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-output-format
Good luck.
6 comments, add yours.
istoica
Thanks for the Proxy clarification, was driving us nuts. But there still are some issues and we cannot execute the function, this due to the integration configuration for method response.
– What do you put at “Method Response” ?
– I see there is a “Proxy” value there, how does that end-up being set ?
joey
context.succeed(res); // we must use this callback to return to amazon api gateway
//callback(null, JSON.stringify(res, null, 2)); // this does not work with the api
I’m doing:
result.body = JSON.stringify(err)
return callback(null, result)
It works fine.
Giridhar
Very well done.. followed what you wrote and worked like charm!! thank you very much for sharing.
Luke
Thanks. This cleared up the 502 bad gateway error. Still struggling with getting my CORS set properly on the API Gateway bleh!
Tan
Thank you for this!
Turns out the gateway really needs the return code and headers. This definitely fixed my issue. Amazon’s code samples weren’t really made for the API trigger I guess
Wei Chen
work like a charm