Eldad Corem
Eldad Corem

Reputation: 11

AWS Api Gateway response mapping regex not working

I'm trying to do a mapping from AWS lambda function response using regex. This is my regex: .*statusCode”:406.*

As you can see - I am trying for it to take a specific mapping from the following response:

{
  "statusCode": 406,
  "body": "{\"aerocrs\":{\"success\":false,\"error_type\":\"request\",\"details\":{\"detail\":\"Incorrect reqyest \",\"errorCode\":4}}}",
  "headers": {
    "x-powered-by": "Express",
    "content-type": "application/json; charset=utf-8",
    "content-length": "116",
    "etag": "W/\"74-Zzo6HU1M1kKkLM9KGtX0jJdePQY\"",
    "date": "Thu, 28 Nov 2019 16:03:05 GMT",
    "connection": "close"
  },
  "isBase64Encoded": false
}

However, I always get to the default mapping. When I change the mapping to .*.*, it gets to the correct one, which makes sense, but for some reason this regex isn't working. Do you have any idea? Thanks!

Upvotes: 0

Views: 485

Answers (2)

Eldad Corem
Eldad Corem

Reputation: 11

I managed to find the issue! Thanks to this great person.

Long story short. AWS Api Gateway is SUPER picky and annoying regarding the error regex. This means, that is looking for a specific structure. Something of this sort:

{
  "errorType": "string",
  "errorMessage": "{\"body\":{\"success\":false,\"error_type\":\"request\",\"details\":{\"errorCode\":4}}}",
  "trace": []
}

So the .*.* does work because it is valid for everything, but even a single letter, like .*s.* is causing an issue. What you need to fix is in your lambda function. In my case - I was using nodeJS function, and aws-serverless-express. The aws-serverless-express is super easy as it works perfectly with express. However, I was using:

awsServerlessExpress.proxy(server, event, context);

Which was enough to return the response ok, but not enough to work with the API gateway's annoying regex. Instead, I changed it to this:

awsServerlessExpress.proxy(server, event, context, 'CALLBACK', function(param1, response){
    if (response.statusCode == 200) {
        //Success
        context.done(response.body);
    }
    else {
        //Fail
        context.fail(response.body);
    }
});

And it worked like a charm. Now I took the response body and return it as success / fail. Then it will work with the format that the lambda function knows how to use.

I hope this will help other people not waste 6 hours on this!

Upvotes: 1

ingernet
ingernet

Reputation: 1524

looks like the output has a space before 406. what happens if you add that space to your regex?

--Edited to add: I use this site all the time (with redacted stuff, naturally) - https://regex101.com/

Upvotes: 0

Related Questions