

# 使用变量来映射 API Gateway 的模板转换的示例
<a name="api-gateway-mapping-variable-examples"></a>

以下示例显示了如何在映射模板中使用 `$context`、`input` 和 `util` 变量。您可以使用模拟集成或用于将输入事件返回到 API Gateway 的 Lambda 非代理集成。有关数据转换的所有支持的变量的列表，请参阅 [API Gateway 的用于数据转换的变量](api-gateway-mapping-template-reference.md)。

## 示例 1：将多个 `$context` 变量传递到集成端点
<a name="context-variables-template-example"></a>

以下示例显示了一个映射模板，该模板将传入的 `$context` 变量映射到后端变量，这些变量在集成请求负载中的名称稍有不同：

```
{
    "stage" : "$context.stage",
    "request_id" : "$context.requestId",
    "api_id" : "$context.apiId",
    "resource_path" : "$context.resourcePath",
    "resource_id" : "$context.resourceId",
    "http_method" : "$context.httpMethod",
    "source_ip" : "$context.identity.sourceIp",
    "user-agent" : "$context.identity.userAgent",
    "account_id" : "$context.identity.accountId",
    "api_key" : "$context.identity.apiKey",
    "caller" : "$context.identity.caller",
    "user" : "$context.identity.user",
    "user_arn" : "$context.identity.userArn"
}
```

此映射模板的输出应与以下内容类似：

```
{
  stage: 'prod',
  request_id: 'abcdefg-000-000-0000-abcdefg',
  api_id: 'abcd1234',
  resource_path: '/',
  resource_id: 'efg567',
  http_method: 'GET',
  source_ip: '192.0.2.1',
  user-agent: 'curl/7.84.0',
  account_id: '111122223333',
  api_key: 'MyTestKey',
  caller: 'ABCD-0000-12345',
  user: 'ABCD-0000-12345',
  user_arn: 'arn:aws:sts::111122223333:assumed-role/Admin/carlos-salazar'
}
```

其中一个变量是 API 密钥。此示例假设方法需要 API 密钥。

## 示例 2：通过 JSON 有效载荷将所有请求参数传递给集成端点
<a name="input-examples-mapping-templates"></a>

以下示例通过 JSON 有效载荷将所有请求参数（包括 `path`、`querystring` 和 `header` 参数）传递到集成端点：

```
#set($allParams = $input.params())
{
  "params" : {
    #foreach($type in $allParams.keySet())
    #set($params = $allParams.get($type))
    "$type" : {
      #foreach($paramName in $params.keySet())
      "$paramName" : "$util.escapeJavaScript($params.get($paramName))"
      #if($foreach.hasNext),#end
      #end
    }
    #if($foreach.hasNext),#end
    #end
  }
}
```

如果请求具有以下输入参数：
+ 名为 `myparam` 的路径参数
+ 查询字符串参数 `querystring1=value1,value2`
+ 标头 `"header1" : "value1"`。

此映射模板的输出应与以下内容类似：

```
{"params":{"path":{"example2":"myparamm"},"querystring":{"querystring1":"value1,value2"},"header":{"header1":"value1"}}}
```

## 示例 3：将方法请求的一部分传递给集成端点
<a name="input-example-json-mapping-template"></a>

 以下示例使用输入参数 `name` 仅检索 `name` 参数，并使用输入参数 `input.json('$')` 检索方法请求的整个正文：

```
{
    "name" : "$input.params('name')",
    "body" : $input.json('$') 
}
```

对于包含查询字符串参数 `name=Bella&type=dog` 和以下正文的请求：

```
{
    "Price" : "249.99",
    "Age": "6"
}
```

此映射模板的输出应与以下内容类似：

```
{
    "name" : "Bella",
    "body" : {"Price":"249.99","Age":"6"}
}
```

此映射模板移除了查询字符串参数 `type=dog`。

 如果 JSON 输入包含无法通过 JavaScript 解析的非转义字符，则 API Gateway 可能会返回 400 响应。应用 `$util.escapeJavaScript($input.json('$'))` 来确保正确解析 JSON 输入。

上面的示例在应用了 `$util.escapeJavaScript($input.json('$'))` 之后会如下所示：

```
{
    "name" : "$input.params('name')",
    "body" : "$util.escapeJavaScript($input.json('$'))"
}
```

在这种情况下，此映射模板的输出应与以下内容类似：

```
{
    "name" : "Bella",
    "body": {"Price":"249.99","Age":"6"}
}
```

## 示例 4：使用 JSONPath 表达式将方法请求的一部分传递给集成端点
<a name="input-example-inputs-mapping-template"></a>

以下示例使用 JSONPath 表达式从请求正文中仅检索输入参数 `name` 和 `Age`：

```
{
    "name" : "$input.params('name')",
    "body" : $input.json('$.Age')  
}
```

对于包含查询字符串参数 `name=Bella&type=dog` 和以下正文的请求：

```
{
    "Price" : "249.99",
    "Age": "6"
}
```

此映射模板的输出应与以下内容类似：

```
{
    "name" : "Bella",
    "body" : "6"
}
```

此映射模板从正文中移除查询字符串参数 `type=dog` 和 `Price` 字段。

 如果方法请求负载包含无法通过 JavaScript 解析的非转义字符，则 API Gateway 可能会返回 `400` 响应。应用 `$util.escapeJavaScript()` 来确保正确解析 JSON 输入。

上面的示例在应用了 `$util.escapeJavaScript($input.json('$.Age'))` 之后会如下所示：

```
{
    "name" : "$input.params('name')",
    "body" : "$util.escapeJavaScript($input.json('$.Age'))" 
}
```

在这种情况下，此映射模板的输出应与以下内容类似：

```
{
    "name" : "Bella",
    "body": "\"6\""
}
```

## 示例 5：使用 JSONPath 表达式将有关方法请求的信息传递到集成端点
<a name="input-example-request-and-response"></a>

以下示例使用 `$input.params()`、`$input.path()` 和 `$input.json()` 向集成端点发送有关方法请求的信息。此映射模板使用 `size()` 方法来提供列表中元素的数量。

```
{
    "id" : "$input.params('id')",
    "count" : "$input.path('$.things').size()",
    "things" : $input.json('$.things')
}
```

对于包含路径参数 `123` 和以下正文的请求：

```
{
      "things": {
            "1": {},
            "2": {},
            "3": {}
      }
}
```

此映射模板的输出应与以下内容类似：

```
{"id":"123","count":"3","things":{"1":{},"2":{},"3":{}}}
```

 如果方法请求负载包含无法通过 JavaScript 解析的非转义字符，则 API Gateway 可能会返回 `400` 响应。应用 `$util.escapeJavaScript()` 来确保正确解析 JSON 输入。

上面的示例在应用了 `$util.escapeJavaScript($input.json('$.things'))` 之后会如下所示：

```
{
     "id" : "$input.params('id')",
     "count" : "$input.path('$.things').size()",
     "things" : "$util.escapeJavaScript($input.json('$.things'))"
}
```

此映射模板的输出应与以下内容类似：

```
{"id":"123","count":"3","things":"{\"1\":{},\"2\":{},\"3\":{}}"}
```