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
Top comments (0)