Event.body LAMBDA_PROXY mapping

Hi there,

I gather from https://serverless.com/framework/docs/providers/aws/events/apigateway/ I need to do something like a:

	if (event.body) {
 		event = JSON.parse(event.body)
 	}

In my code?

I am quite familiar with doing something like a sls invoke -f dosomething -p events/notification.json locally, so I am little bit bewildered by this kludge needed for the event object when using the “http” event.

Please let me know if I am going crazy.

The Lambda Proxy integration is still relatively new, so it’s not without its rough edges.

As the content could be JSON - or it could not - there’s currently no assumption made about the content type. If it’s JSON, treat it like serialised JSON. The service makes no attempt to read the headers and work out the content type for you.

Now that you mention it, that sounds like a good idea for a PR…

Hey @hendry

I’ll assume your building an API that only accepts JSON.

The input is a serialized JSON object so you’re not going crazy. I’ve been using the following:

try {
    const json = JSON.parse(event.body);

    // YOUR CODE HERE

} catch (e) {
    console.error(e);
    callback(null, { statusCode: 500, headers: { "Content-Type": "application/json"}, body: JSON.stringify({ message: "Internal Error" }) });
}

Any uncaught exceptions, which could include de-serializing the JSON, result in a 500 error.

Oh but the point I was trying to make is that usually that comes down as the event in my other lambda functions, so this inconsistency RE API gateway is a bit annoying.

The event is specific to the source. With Lambda proxy your Lambda is processing a generic HTTP request so this approach makes sense. The user could be sending XML, HTTP POST parameters or anything they want in the body. The only way the Lambda proxy integration can deal with every possibility is to pass the entire request to the Lambda and let it deal with it. That’s why you need parse the body first.

If you want to receive a JSON object then you should switch from Lambda proxy to Lambda integration.

The reason I said about only accepting JSON is so that I didn’t need to check the Content-Type header first.