Understanding mapping templates
In API Gateway, an API's method request or response can take a payload in a different format from the integration request or response.
You can transform your data to:
Match the payload to an API-specified format.
Override an API's request and response parameters and status codes.
Return client selected response headers.
Associate path parameters, query string parameters, or header parameters in the method request of HTTP proxy or AWS service proxy.
Select which data to send using integration with AWS services, such as Amazon DynamoDB or Lambda functions, or HTTP endpoints.
You can use mapping templates to transform your data. A mapping template is a script
expressed in Velocity Template Language
(VTL)
The following example shows
input data, a mapping template, and output data for a transformation of the PetStore data
Input data |
|
Mapping template |
|
Output data |
|
The following diagram shows details of this mapping template.
The
$inputRoot
variable represents the root object in the original JSON data from the previous section. Directives begin with the#
symbol.A
foreach
loop iterates though each object in the original JSON data.The description is a concatenation of the Pet's
id
andtype
from the original JSON data.askingPrice
is theprice
is the price from the original JSON data.
1 #set($inputRoot = $input.path('$')) 2 [ 3 #foreach($elem in $inputRoot) 4 { 5 "description" : "Item $elem.id is a $elem.type.", 6 "askingPrice" : $elem.price 7 }#if($foreach.hasNext),#end 8 #end 9 ]
In this mapping template:
-
On line 1, the
$inputRoot
variable represents the root object in the original JSON data from the previous section. Directives begin with the#
symbol. -
On line 3, a
foreach
loop iterates through each object in the original JSON data. -
On line 5, the
description
is a concatenation of the Pet'sid
andtype
from the original JSON data. -
On line 6,
askingPrice
is theprice
is the price from the original JSON data.
For more information about the Velocity Template Language, see Apache
Velocity - VTL Reference
The mapping template assumes that the underlying data is of a JSON object. It does not require that a model be defined for the data. However, a model for the output data allows preceding data to be returned as a language-specific object. For more information, see Understanding data models.
Complex mapping templates
You can also create more complicated mapping templates. The following example shows the concatenation of references and a cutoff of 100 to determine if a pet is affordable.
Input data |
|
Mapping template |
|
Output data |
|
See the example photo album Photos example for a more complicated model.