Create Models and Mapping Templates for Request and Response Mappings
In API Gateway, an API's method request can take a payload in a different format from the corresponding integration request payload, as required in the backend. Similarly, the backend may return an integration response payload different from the method response payload, as expected by the frontend. API Gateway lets you use mapping templates to map the payload from a method request to the corresponding integration request and from an integration response to the corresponding method response.
A mapping template is a script expressed in Velocity Template Language (VTL) and applied to the payload using JSONPath expressions. The payload can have a data model according to the JSON Schema. You must define the model in order to have API Gateway to generate a SDK or to enable basic request validation for your API. You do not have to define any model to create a mapping template. However, a model can help you create a template because API Gateway will generate a template blueprint based on a provided model.
The section explains how to map the API request and response payload using models and mapping templates.
Topics
- Models
- Mapping Templates
- Tasks for Models and Mapping Templates
- Create a Model in API Gateway
- View a List of Models in API Gateway
- Delete a Model in API Gateway
- Photos Example (API Gateway Models and Mapping Templates)
- News Article Example (API Gateway Models and Mapping Templates)
- Sales Invoice Example (API Gateway Models and Mapping Templates)
- Employee Record Example (API Gateway Models and Mapping Templates)
Models
In API Gateway, a model defines the data structure of a payload. In API Gateway models are defined using the JSON Schema.
The following JSON object describes a sample data describing the fruit or vegetable inventory in the produce department of a likely supermarket:
Suppose we have an API for managing fruit and vegetable inventory in the produce department of a supermarket. When a manager queries the backend for the current inventory, the server sends back the following response payload:
Copy{ "department": "produce", "categories": [ "fruit", "vegetables" ], "bins": [ { "category": "fruit", "type": "apples", "price": 1.99, "unit": "pound", "quantity": 232 }, { "category": "fruit", "type": "bananas", "price": 0.19, "unit": "each", "quantity": 112 }, { "category": "vegetables", "type": "carrots", "price": 1.29, "unit": "bag", "quantity": 57 } ] }
The JSON object has three properties
-
The
departmentproperty has a string value (produce). -
The
categoriesproperty is an array of two strings:fruitandvegetables. -
The
binsproperty is an array of objects, each having the string- or number-valued properties ofcategory,type,price,unitandquantity.
We can use the following JSON Schema to define the model for the above data:
Copy{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "GroceryStoreInputModel", "type": "object", "properties": { "department": { "type": "string" }, "categories": { "type": "array", "items": { "type": "string" } }, "bins": { "type": "array", "items": { "type": "object", "properties": { "category": { "type": "string" }, "type": { "type": "string" }, "price": { "type": "number" }, "unit": { "type": "string" }, "quantity": { "type": "integer" } } } } } }
In the preceding example model:
-
The
$schemaobject represents a valid JSON Schema version identifier. In this example, it refers to JSON Schema, draft v4. -
The
titleobject is a human-readable identifier for the model. In this example, it isGroceryStoreInputModel. -
The top-level, or root, construct in the JSON data is an object.
-
The root object in the JSON data contains
department,categories, andbinsproperties. -
The
departmentproperty is a string object in the JSON data. -
The
categoriesproperty is an array in the JSON data. The array contains string values in the JSON data. -
The
binsproperty is an array in the JSON data. The array contains objects in the JSON data. Each of these objects in the JSON data contains acategorystring, atypestring, apricenumber, aunitstring, and aquantityinteger (a number without a fraction or exponent part).
Alternatively, you could include part of this schema, for example, the item definition
of the bins array, in a separate section of the same file and use the $ref primitive to reference this reusable definition in other parts of the schema. Using
$ref, the above model definition file can be expressed as follows:
Copy{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "GroceryStoreInputModel", "type": "object", "properties": { "department": { "type": "string" }, "categories": { "type": "array", "items": { "type": "string" } }, "bins": { "type": "array", "items": { "$ref": "#/definitions/Bin" } } }, "definitions": { "Bin" : { "type": "object", "properties": { "category": { "type": "string" }, "type": { "type": "string" }, "price": { "type": "number" }, "unit": { "type": "string" }, "quantity": { "type": "integer" } } } } }
The definitions section contains the schema definition of the Bin item that is referenced in the bins array with "ref": "#/definitions/Bin". Using reusable definitions this way makes your model definition easier to read.
In addition, you can also reference another model schema defined in an external model
file by setting that model's URL as the value of the $ref property: "$ref": "https://apigateway.amazonaws.com/restapis/{restapi_id}/models/{model_name}". For example, supposed you have the following full-fledged model named Bin2 created under an API with an identifier of fugvjdxtri:
Copy{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "GroceryStoreInputModel", "type": "object", "properties": { "Bin" : { "type": "object", "properties": { "category": { "type": "string" }, "type": { "type": "string" }, "price": { "type": "number" }, "unit": { "type": "string" }, "quantity": { "type": "integer" } } } } }
You can then reference it from the GroceryStoreInputModel from the same API, as shown as follows:
Copy{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "GroceryStoreInputModel", "type": "object", "properties": { "department": { "type": "string" }, "categories": { "type": "array", "items": { "type": "string" } }, "bins": { "type": "array", "items": { "$ref": "https://apigateway.amazonaws.com/restapis/fugvjdxtri/models/Bin2" } } } }
The referencing and referenced models must be from the same API.
The examples do not use advanced JSON Schema features, such as specifying required items; minimum and maximum allowed string lengths, numeric values, and array item lengths; regular expressions; and more. For more information, see Introducing JSON and JSON Schema.
For more complex JSON data formats and their models, see the following examples:
-
Input Model (Photos Example) and Output Model (Photos Example) in the Photos Example
-
Input Model (News Article Example) and Output Model (News Article Example) in the News Article Example
-
Input Model (Sales Invoice Example) and Output Model (Sales Invoice Example) in the Sales Invoice Example
-
Input Model (Employee Record Example) and Output Model (Employee Record Example) in the Employee Record Example
To experiment with models in API Gateway, follow the instructions in Map Response Payload, specifically Step 1: Create Models.
Mapping Templates
When the backend returns the query results (shown in the Models section), the manager of the produce department may be interested in reading them as follows:
Copy{ "choices": [ { "kind": "apples", "suggestedPrice": "1.99 per pound", "available": 232 }, { "kind": "bananas", "suggestedPrice": "0.19 per each", "available": 112 }, { "kind": "carrots", "suggestedPrice": "1.29 per bag", "available": 57 } ] }
To enable this, we need to provide API Gateway a mapping template to translate the data from the backend format. The following mapping template will do just that.
Copy#set($inputRoot = $input.path('$')) { "choices": [ #foreach($elem in $inputRoot.bins) { "kind": "$elem.type", "suggestedPrice": "$elem.price per $elem.unit", "available": $elem.quantity }#if($foreach.hasNext),#end #end ] }
Let us now examine some details of the preceding output mapping template:
-
The
$inputRootvariable represents the root object in the original JSON data from the previous section. The variables in an output mapping template map to the original JSON data, not the desired transformed JSON data schema. -
The
choicesarray in the output mapping template is mapped from thebinsarray with the root object in the original JSON data ($inputRoot.bins). -
In the output mapping template, each of the objects in the
choicesarray (represented by$elem) are mapped from the corresponding objects in thebinsarray within the root object in the original JSON data. -
In the output mapping template, for each of objects in the
choicesobject, the values of thekindandavailableobjects (represented by$elem.typeand$elem.quantity) are mapped from the corresponding values of thetypeandvalueobjects in each of the objects in the original JSON data'sbinsarray, respectively. -
In the output mapping template, for each of objects in the
choicesobject, the value of thesuggestedPriceobject is a concatenation of the corresponding value of thepriceandunitobjects in each of the objects in the original JSON data, respectively, with each value separated by the wordper.
For more information about the Velocity Template Language, see Apache Velocity - VTL Reference. For more information about JSONPath, see JSONPath - XPath for JSON.
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. As an API developer, you know the data formats at both the front and backends. That knowledge can guide you to define the necessary mappings without ambiguity.
To have an SDK generated for the API, the above data will be returned as a language-specific object. For strongly typed languages, such as Java, Objective-C or Swift, the object corresponds to a user-defined data type (UDT). API Gateway will create such a UDT if you provide it with a data model. For the method response example above, you can define the following payload model in the integration response:
Copy{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "GroceryStoreOutputModel", "type": "object", "properties": { "choices": { "type": "array", "items": { "type": "object", "properties": { "kind": { "type": "string" }, "suggestedPrice": { "type": "string" }, "available": { "type": "integer" } } } } } }
In this model, the JSON schema is expressed as follows:
-
The
$schemaobject represents a valid JSON Schema version identifier. In this example, it refers to JSON Schema, draft v4. -
The
titleobject is a human-readable identifier for the model. In this example, it isGroceryStoreOutputModel. -
The top-level, or root, construct in the JSON data is an object.
-
The root object in the JSON data contains an array of objects.
-
Each object in the array of objects contains a
kindstring, asuggestedPricestring, and anavailableinteger (a number without a fraction or exponent part).
With this model, you can call an SDK to retrieve the kind, suggestedPrice and available property values by reading the GroceryStoreOutputModel.kind, GroceryStoreOutputModel.suggestedPrice and GroceryStoreOutputModel.available properties, respectively. If no model is provided, API Gateway will use the Empty
model to create a default UDT. In this case, you will not be able to read these properties
using a strongly-typed SDK.
To explore more complex mapping templates, see the following examples:
-
Input Mapping Template (Photos Example) and Output Mapping Template (Photos Example) in the Photos Example
-
Input Mapping Template (News Article Example) and Output Mapping Template (News Article Example) in the News Article Example
-
Input Mapping Template (Sales Invoice Example) and Output Mapping Template (Sales Invoice Example) in the Sales Invoice Example
-
Input Mapping Template (Employee Record Example) and Output Mapping Template (Employee Record Example) in the Employee Record Example
To experiment with mapping templates in API Gateway, follow the instructions in Map Response Payload, specifically Step 5: Set up and Test the Methods.
Tasks for Models and Mapping Templates
For additional things you can do with models and mapping templates, see the following:


