本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
在 API Gateway 中,API 的方法請求或回應可從整合請求或回應中取得不同格式的承載。
您可以轉換資料:
使承載符合 API 指定的格式。
覆寫 API 請求與回應參數和狀態碼。
傳回用戶端選取的回應標頭。
在 HTTP 代理或 AWS 服務 代理的方法請求中關聯路徑參數、查詢字串參數或標頭參數。
使用整合選取要傳送的資料 AWS 服務,例如 Amazon DynamoDB 或 Lambda 函數或 HTTP 端點。
您可以使用對應範本轉換資料。對應範本是以 Velocity 範本語言 (VTL)
本節說明與映射範本相關的概念性資訊。如需有關為 API Gateway REST API 建立映射範本的說明,請參閱 在 API Gateway 中設定資料轉換。
映射範本範例
下列範例是將資料輸入至整合請求。
[ { "id": 1, "type": "dog", "price": 249.99 }, { "id": 2, "type": "cat", "price": 124.99 }, { "id": 3, "type": "fish", "price": 0.99 } ]
下列範例是用於轉換整合請求資料的映射範本。
#set($inputRoot = $input.path('$')) [ #foreach($elem in $inputRoot) { "description" : "Item $elem.id is a $elem.type.", "askingPrice" : $elem.price }#if($foreach.hasNext),#end #end ]
下列範例是轉換的輸出資料。
[ { "description" : "Item 1 is a dog.", "askingPrice" : 249.99 }, { "description" : "Item 2 is a cat.", "askingPrice" : 124.99 }, { "description" : "Item 3 is a fish.", "askingPrice" : 0.99 } ]
下圖顯示此對應範本的詳細資訊。

$inputRoot
變數代表上一節中原始 JSON 資料的根物件。指令以#
符號開始。foreach
迴圈逐一處理原始 JSON 資料中的每個物件。描述是來自原始 JSON 資料的寵物
id
和type
串連。askingPrice
是price
(來自原始 JSON 資料的價格)。
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 ]
在此對應範本中:
-
在第 1 行,
$inputRoot
變數代表上一節中原始 JSON 資料的根物件。指令以#
符號開始。 -
在第 3 行,
foreach
迴圈逐一處理原始 JSON 資料中的每個物件。 -
在第 5 行,
description
是來自原始 JSON 資料的寵物id
和type
串連。 -
在第 6 行,
askingPrice
是price
(來自原始 JSON 資料的價格)。
如需 Velocity 範本語言的詳細資訊,請參閱 Apache Velocity - VTL Reference
對應範本假設基礎資料屬於 JSON 物件。它不需要定義資料模型。不過,輸出資料的模型允許以語言特定物件的形式傳回先前的資料。如需詳細資訊,請參閱REST API 的資料模型。
複雜的映射範本範例
您也可以建立更複雜的對應範本。下列範例說明用來判斷是否養得起寵物的參考串連和取捨點 (100)。
下列範例是將資料輸入至整合請求。
[ { "id": 1, "type": "dog", "price": 249.99 }, { "id": 2, "type": "cat", "price": 124.99 }, { "id": 3, "type": "fish", "price": 0.99 } ]
下列範例是用於轉換整合請求資料的映射範本。
#set($inputRoot = $input.path('$')) #set($cheap = 100) [ #foreach($elem in $inputRoot) { #set($name = "${elem.type}number$elem.id") "name" : $name, "description" : "Item $elem.id is a $elem.type.", #if($elem.price > $cheap )#set ($afford = 'too much!') #{else}#set ($afford = $elem.price)#end "askingPrice" : $afford }#if($foreach.hasNext),#end #end ]
下列範例是轉換的輸出資料。
[ { "name" : dognumber1, "description" : "Item 1 is a dog.", "askingPrice" : too much! }, { "name" : catnumber2, "description" : "Item 2 is a cat.", "askingPrice" : too much! }, { "name" : fishnumber3, "description" : "Item 3 is a fish.", "askingPrice" : 0.99 } ]
您也會看到更複雜的資料模型。請參閱 適用於 API Gateway 的範例資料模型和映射範本。