13

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?

Henders
  • 1,195
  • 1
  • 21
  • 27
magnus123
  • 270
  • 1
  • 3
  • 9

2 Answers2

6

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"}
Community
  • 1
  • 1
tomodian
  • 6,043
  • 4
  • 25
  • 29
0

Try changing your template to this:

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

$input.json('$') is supposed to represent the JSON object returned by lambda.

Arlo Carreon
  • 441
  • 1
  • 4
  • 11