

# 使用 API Gateway 控制台启用模拟集成
<a name="how-to-mock-integration-console"></a>

您必须在 API Gateway 中有一个可用的方法。按照[教程：使用 HTTP 非代理集成创建 REST API](api-gateway-create-api-step-by-step.md)中的说明进行操作。

1. 选择 API 资源，然后选择**创建方法**。

   要创建方法，请执行以下操作：

   1. 对于**方法类型**，选择一种方法。

   1. 对于**集成类型**，选择**模拟**。

   1. 选择**创建方法**。

   1. 在**方法请求**选项卡上，对于**方法请求设置**，选择**编辑**。

   1. 选择 **URL 查询字符串参数**。选择**添加查询字符串**，然后为**名称**中输入 **scope**。此查询参数确定调用方是否为内部。

   1. 选择**保存**。

1. 在**方法响应**选项卡上，选择**创建响应**，然后执行以下操作：

   1. 对于 **HTTP 状态**，输入 **500**。

   1. 选择**保存**。

1. 在**集成请求**选项卡上，对于**集成请求设置**，选择**编辑**。

1. 选择**映射模板**，然后执行以下操作：

   1. 选择**添加映射模板**。

   1. 对于**内容类型**，输入 **application/json**。

   1. 对于**模板正文**，输入以下内容：

      ```
      {
        #if( $input.params('scope') == "internal" )
          "statusCode": 200
        #else
          "statusCode": 500
        #end
      }
      ```

   1. 选择**保存**。

1. 在**集成响应**选项卡上，对于**默认 - 响应**，选择**编辑**。

1. 选择**映射模板**，然后执行以下操作：

   1. 对于**内容类型**，输入 **application/json**。

   1. 对于**模板正文**，输入以下内容：

      ```
      {
          "statusCode": 200,
          "message": "Go ahead without me"
      }
      ```

   1. 选择**保存**。

1. 选择**创建响应**。

   要创建 500 响应，请执行以下操作：

   1. 对于 **HTTP 状态正则表达式**，输入 **5\$1d\$12\$1**。

   1. 对于**方法响应状态**，选择 **500**。

   1. 选择**保存**。

   1. 对于 **5\$1d\$12\$1 - 响应**，选择**编辑**。

   1. 选择**映射模板**，然后选择**添加映射模板**。

   1. 对于**内容类型**，输入 **application/json**。

   1. 对于**模板正文**，输入以下内容：

      ```
      {
          "statusCode": 500,
          "message": "The invoked method is not supported on the API resource."
      }
      ```

   1. 选择**保存**。

1.  选择**测试**选项卡。您可能需要选择右箭头按钮，以显示该选项卡。要测试模拟集成，请执行以下操作：

   1. 在**查询字符串**下，输入 `scope=internal`。选择 **Test (测试)**。测试结果显示：

      ```
      Request: /?scope=internal
      Status: 200
      Latency: 26 ms
      Response Body
      
      {
        "statusCode": 200,
        "message": "Go ahead without me"
      }
      
      Response Headers
      
      {"Content-Type":"application/json"}
      ```

   1. 在 `scope=public` 下输入 `Query strings` 或将其留空。选择 **Test (测试)**。测试结果显示：

      ```
      Request: /
      Status: 500
      Latency: 16 ms
      Response Body
      
      {
        "statusCode": 500,
        "message": "The invoked method is not supported on the API resource."
      }
      
      Response Headers
      
      {"Content-Type":"application/json"}
      ```

您也可以首先将标头添加到方法响应，然后在集成响应中设置标头映射，从而在模拟集成响应中返回标头。实际上，这是 API Gateway 控制台通过返回 CORS 需要的标头来启用 CORS 支持的方法。