Search code examples
aws-api-gatewayapi-gateway

API Gateway: Insert requestId into request body using mapping template


In AWS Api Gateway, I want to insert the generated requestId into the request body without having to manually type each entry in the original request body.

If this is the original request body:

{
  "name": "name",
  "age": "20",
  ...
}

Then I want to transform it into:

{
  "name": "name",
  "age": "20",
  ...,
  "requestId": $context.requsetId
}

I do realize that there is an option of inserting the id into the header, but I want to insert the requestId into the body instead. I also want to avoid typing each key-value in the original body because I want the requestId to be inserted regardless of the body structure.


Solution

  • You can use mapping templates to add the requestId to the request body.

    I also want to avoid typing each key-value in the original body because I want the requestId to be inserted regardless of the body structure

    You can use a template like this for that:

    #set($inputRoot = $input.path('$'))
    {
      #foreach($key in $inputRoot.keySet())
        "$key": "$inputRoot.get($key)"
        #if($foreach.hasNext),#end
      #end,
      "requestId":"$context.requestId"
    }