使用 API Gateway 控制台为 REST API 设置网关响应
使用 API Gateway 控制台自定义网关响应
-
登录 API Gateway 控制台。
选择一个 REST API。
-
在主导航窗格中,选择 API 下的网关响应。
-
在 Gateway Responses (网关响应) 窗格中,选择响应类型。在本次演练中,我们将以 Missing Authentication Token (403) (缺失身份验证令牌 (403)) 为例。
-
您可以更改 API Gateway 生成的状态代码,以返回满足您的 API 要求的不同状态代码。在此示例中,自定义会将状态代码从默认值 (
403
) 更改为404
,因为在客户端调用可被视为未找到的不受支持或无效的资源时,会出现此错误消息。 -
要返回自定义标头,请选择 Response Headers (响应标头) 下的 Add Header (添加标头)。为方便说明,我们将添加以下自定义标头:
Access-Control-Allow-Origin:'a.b.c' x-request-id:method.request.header.x-amzn-RequestId x-request-path:method.request.path.petId x-request-query:method.request.querystring.q
在前面的标头映射中,将静态域名 (
'a.b.c'
) 映射到Allow-Control-Allow-Origin
标头以允许 CORS 访问 API;将x-amzn-RequestId
的输入请求标头映射到响应中的request-id
;将传入请求的petId
路径变量映射到响应中的request-path
标头;以及将原始请求的q
查询参数映射到响应的request-query
标头。 -
在 Mapping Templates(映射模板)下,将
application/json
保留为 Content Type(内容类型),然后在 Body Mapping Template(正文映射模板)编辑器中输入以下正文映射模板:{ "message":"$context.error.messageString", "type": "$context.error.responseType", "statusCode": "'404'", "stage": "$context.stage", "resourcePath": "$context.resourcePath", "stageVariables.a": "$stageVariables.a" }
此示例显示了如何将
$context
和$stageVariables
属性映射到网关响应正文的属性。 -
选择保存。
-
将 API 部署到新阶段或现有阶段。
-
通过调用以下 CURL 命令并假设相应 API 方法的调用 URL 是
https://o81lxisefl.execute-api.us-east-1.amazonaws.com/custErr/pets/{petId}
,进行测试:curl -v -H 'x-amzn-RequestId:123344566' https://o81lxisefl.execute-api.us-east-1.amazonaws.com/custErr/pets/5/type?q=1
因为额外查询字符串参数
q=1
与 API 不兼容,所以返回错误,从而触发指定的网关响应。您应收到与以下内容类似的网关响应:> GET /custErr/pets/5?q=1 HTTP/1.1 Host: o81lxisefl.execute-api.us-east-1.amazonaws.com User-Agent: curl/7.51.0 Accept: */* HTTP/1.1 404 Not Found Content-Type: application/json Content-Length: 334 Connection: keep-alive Date: Tue, 02 May 2017 03:15:47 GMT x-amzn-RequestId: 123344566 Access-Control-Allow-Origin: a.b.c x-amzn-ErrorType: MissingAuthenticationTokenException header-1: static x-request-query: 1 x-request-path: 5 X-Cache: Error from cloudfront Via: 1.1 441811a054e8d055b893175754efd0c3.cloudfront.net (CloudFront) X-Amz-Cf-Id: nNDR-fX4csbRoAgtQJ16u0rTDz9FZWT-Mk93KgoxnfzDlTUh3flmzA== { "message":"Missing Authentication Token", "type": MISSING_AUTHENTICATION_TOKEN, "statusCode": '404', "stage": custErr, "resourcePath": /pets/{petId}, "stageVariables.a": a }
前面的示例假定 API 后端为 Pet Store
,并且 API 有一个定义的阶段变量 a
。