8
votes

I could set single http response header through api gateway integration response header mapping.
in that case i was giving context.fail("http://www.google.com") response from aws lambda and use regex (".http.") to identify the response and finally map it to my header like this
Location: integration.response.body.errorMessage.
This is working when i try to map a single header at a time.
But i want to set both Location and Cookie headers in a single response. to achieve this, i returned a json from my aws lambda like

context.fail(JSON.stringify({Location:"http://www.google.com",Cookie: vid="233kwer34343"})) 

but i couldn't map headers via integration.response.body.errorMessage.Location and integration.response.body.errorMessage.Cookie

It is possible to do this by using context.succeed() instead of context.fail() . but this is not checking regex. i want to check regex for categorizing responses.

What is the best way to map multiple response headers from lambda response body?

2

2 Answers

0
votes

This is not because of API Gateway or multiple headers. Please note that the Location header will be added to the Response only for redirect (3xx) or successfull process (2xx) of the request. It will not be added when return code is error (4xx, 5xx) etc.

More details here - https://en.wikipedia.org/wiki/HTTP_location

This the reason why it worked for context.succeed() and it did not work for context.fail().

0
votes

I don't think you can make this working using context.fail. The problem is that the parameter passed to context.fail is a simple string. That string is then encoded into a json string and then passed to API Gateway as a sting value within an attribute named "errorMessage".

The response body coming from Lambda looks something like this: {"errorMessage": "{\"Location\":\"http://www.google.com\",\"Cookie\": \"vid='233kwer34343'\"}"}

Note that the value of errorMessage is a string with the special characters escaped, rather than a json object. There's no way to tell a header mapping to look in integration.response.body.errorMessage, parse that string into json, and grab the location attribute of the resulting json object.

If you were returning the values as a response body, rather than as headers, then you could use velocity to parse the contents of errorMessage and transform them into whatever response body you like. Unfortunately, header mappings don't have the full processing power/flexibility of the velocity templates.

Why do you need to call context.fail in this case?

If you call context.done you can return json as the body like: {"Location":"http://www.google.com","Cookie": "vid='233kwer34343'"}

Then the header mappings are just integration.response.body.Location and integration.response.body.Cookie