Transforming payload with VTL in API Gateway — EventBridge integration

This article assumes you already have a working integration between AWS API Gateway and Amazon EventBridge.

It seems like you’re really trying to avoid using another lambda to handle the payload transformation. Good choice*. The number of lambdas in a serverless infrastructure can quickly get out-of-hand and you should avoid creating unnecessary resources whenever it’s possible.

Amazon REST API Gateway offers a solution in the form of Mapping templates. The basic passthrough integration looks as follows:

  • DetailType: Identifies, in combination with the Source field, the fields and values that appear in the Detail field.
  • Source: Identifies the service that generated the event.
  • EventBusName: The name of the targeted event bus.
  • Detail: The payload of the event (this field is where it gets tricky).

What do we want to achieve?

Imagine that some third party is sending unstructured, strange looking data to your API.

Before the payload hits the EventBridge, you want it to look like this:

Nice and clean, without the BDAS_4333 field that you don’t even need.

The transformation

Folks at AWS have decided that you’d use VTL to handle the transformation. The whole stumbling-block is that EventBridge expects the value of Detail field as a stringified, escaped JSON.

For such an easy transformation you could write the Mapping template inline:

To handle the transformation of our example, the Mapping template can look as such:

Whoa, that’s a big jump. Let’s break it down.

  1. First we save the incoming payload in $inputRoot variable.
  2. We map the incoming $inputRoot.eventType to one of our desired values (ITEM_PURCHASED or ITEM_RETURNED) and save it in $event variable.
  3. Extract all the desired fields and wrap them in double quotes.
  4. Construct $customerMap, $addressMap and $purchaseMap maps.
  5. Construct the $payloadMap.
  6. Finally we stringify the $payloadMap. Since VTL map uses “=” instead of “:” to separate key-value pairs we’ll need to call .replace(“=”, “:”) on the stringified map.


As you’ve probably noticed by now, working with VTL Mapping template is no picnic. Extracting the variables and wrapping them in double quotes seems messy, but it was the only approach that kept the code somehow structured. Make sure that your VTL syntax is on point. Leaving one trailing comma inside map would break the whole thing. Or save yourself some time and use a lambda instead.

A software development blog by the folks at