API Gateway append custom data to mapping template input.json

prabusah_53

Prabusah

Posted on February 20, 2022

API Gateway append custom data to mapping template input.json

Requirement:

  • AWS API Gateway has a AWS Lambda integration.
  • Append custom data to input json via mapping template.
  • Event json sent to Lambda should be simple json (Not a nested json).
  • Please Note: Nothing wrong in passing nested json to Integrated Lambda. This post discussing about a requirement to pass only simple json to the Lambda.

API Gateway user provided input json.

{
  "name": "John",
  "phoneNumber": "1231231231"
}
Enter fullscreen mode Exit fullscreen mode

Expected json output

after appending Custom data: ("code" : "abcd")

{
  "name": "John",
  "phoneNumber": "1231231231",
  "code": "abcd"
}
Enter fullscreen mode Exit fullscreen mode

Solution option1: (Not meeting requirement)
AWS Console -> API Gateway -> Select a Resource -> Integration Request -> Mapping Templates -> "When thee are no templates defined" -> Content Type: application/json -> provide below template

{
"body": $input.json('$'),
"code": "abcd"
}
Enter fullscreen mode Exit fullscreen mode

AWS Lambda event appears as below:

{
  "body": {
    "name": "John",
    "phoneNumber": "1231231231"
  },
  "code": "abcd"
}
Enter fullscreen mode Exit fullscreen mode

The above json is not meeting with expected json format mentioned in our requirements stated above.

Solution option2: (meets the expectation):
AWS Console -> API Gateway -> Select a Resource -> Integration Request -> Mapping Templates -> "When thee are no templates defined" -> Content Type: application/json -> provide below template

#set($elem = $util.parseJson($input.json('$')))
{
#foreach($elemKey in $elem.keySet())
    "$elemKey": "$elem.get($elemKey)"
    #if($foreach.hasNext),#end
,
"code": "abcd"
}
Enter fullscreen mode Exit fullscreen mode

AWS Lambda event appears as below:

{
  "name": "John",
  "phoneNumber": "1231231231",
  "code": "abcd"
}
Enter fullscreen mode Exit fullscreen mode

Conclusion:

In real scenario the custom data can be output of Lambda authorizer data getting appended to input json and passed on to Integrated AWS Lambda as event.

Image by Gerd Altmann from Pixabay

💖 💪 🙅 🚩
prabusah_53
Prabusah

Posted on February 20, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related