API Gateway append custom data to mapping template input.json
Prabusah
Posted on February 20, 2022
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"
}
Expected json output
after appending Custom data: ("code" : "abcd")
{
"name": "John",
"phoneNumber": "1231231231",
"code": "abcd"
}
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"
}
AWS Lambda event appears as below:
{
"body": {
"name": "John",
"phoneNumber": "1231231231"
},
"code": "abcd"
}
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"
}
AWS Lambda event appears as below:
{
"name": "John",
"phoneNumber": "1231231231",
"code": "abcd"
}
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
Posted on February 20, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.