使用 API Gateway 控制台启用模拟集成
方法在 API Gateway 中必须可用。按照中的说明进行操作教程:使用 HTTP 非代理集成构建 REST API
-
选择 API 资源并创建方法。在方法设置窗格中,为 Integration type (集成类型) 选择 Mock (模拟),然后选择保存。
-
从 Method Execution (方法执行) 选择 Method Request (方法请求)。展开 URL Query String Parameters (URL 查询字符串参数)。选择 Add query string (添加查询字符串) 以添加
scope
查询参数。这确定调用方是否为内部。 -
从 Method Execution (方法执行) 中,选择 Method Response (方法响应)。
-
在 HTTP Status (HTTP 状态) 下,添加
500
。 -
从 Method Execution (方法执行) 选择 Integration Request (集成请求)。展开 Mapping Templates (映射模板)。选择或添加 application/json 映射模板。在模板编辑器中输入以下内容:
{ #if( $input.params('scope') == "internal" ) "statusCode": 200 #else "statusCode": 500 #end }
选择保存。
-
从 Method Execution (方法执行) 选择 Integration Response (集成响应)。展开 200 响应,然后选择 Mapping Templates (映射模板) 部分。选择或添加应用程序/json 映射模板,然后在模板编辑器中输入以下响应正文映射模板。
{ "statusCode": 200, "message": "Go ahead without me" }
选择保存。
-
选择 Add integration response (添加集成响应) 以添加 500 响应。在 HTTP status regex (HTTP 状态正则表达式) 中输入
5\d{2}
。对于 Method response status (方法响应状态),选择500
,然后选择 Save (保存)。 -
展开 5\d{2},然后展开 Mapping Templates (映射模板) 并选择 Add mapping template (添加映射模板)。为 Content-Type (内容-类型) 输入
application/json
,然后选择对勾图标以保存设置。在模板编辑器中,输入以下集成响应正文映射模板:{ "statusCode": 500, "message": "The invoked method is not supported on the API resource." }
选择保存。
-
从 Method Execution (方法执行) 中选择 测试。执行以下操作:
-
在 Query Strings (查询字符串) 下,输入
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"}
-
在
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 支持的方法。