Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return JSON with Lambda through API Gateway with mapping

I am trying to figure out how to map a Response from Lambda in the API Gateway to different status codes and at the same time receive a JSON object from my Lambda-function.

I have the following in Lambda:

context.done('Not Found:',jsonObject);

And in my API Gateway, in integration response I have a Lambda error regex on 403 saying Not Found:.*. This works, the method is returning a returning a 403.

The problem is I can't seem to return the jsonObject. I have tried to create a application/json mapping template that looks like this (also under integration response):

{"error" : $input.json('$')}

But that only results in my response looking like this:

{"error" : {"errorMessage":"Not Found:"}}

Am I misunderstanding the mapping template?

like image 419
mysanders Avatar asked Oct 29 '15 09:10

mysanders


People also ask

How do I return HTML from AWS API gateway and Lambda?

Navigate to the Integration Response for the API's GET method. Open up the 200 Response, Header Mappings, and Mapping Templates. Edit the Response Header Content-Type and set the Mapping value to 'text/html' (be sure to use single quotes). Don't forget to save it with the green checkmark icon.


1 Answers

If you want to stick with Lambda's default binding behavior, this approach looks promising.

Is there a way to change the http status codes returned by Amazon API Gateway?

Also Lambda will ignore the second parameter if the first error parameter is non-null.

Here's some cases how Lambda works.

Case 1: The first parameter is null.

exports.handler = function(event, context) {
  context.done(null, {hello: 'world'});
}

Result: Lambda only returns the second parameter in JSON object.

{"hello": "world"}

Case 2: The first parameter is non-null object.

exports.handler = function(event, context) {
  context.done({ping: 'pong'}, {hello: 'world'});
}

Result: Lambda automatically binds the first parameter to errorMessage value. Notice the second parameter {hello: 'world'} is dropped off.Better not to pass object as it results in [object Object].

{"errorMessage": "[object Object]"}

Case 3: The first parameter is non-null string.

exports.handler = function(event, context) {
  context.done('pingpong', {hello: 'world'});
}

Result: Lambda automatically binds the first parameter to errorMessage value. Notice the second parameter {hello: 'world'} is dropped off.

{"errorMessage": "pingpong"}
like image 155
tomodian Avatar answered Oct 05 '22 10:10

tomodian