使用 API Gateway 控制台为 REST API 设置网关响应 - Amazon API Gateway

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 API Gateway 控制台为 REST API 设置网关响应

使用 API Gateway 控制台自定义网关响应
  1. 通过以下网址登录到 Amazon API Gateway 控制台:https://console.aws.amazon.com/apigateway

  2. 选择一个 REST API。

  3. 在主导航窗格中,选择网关响应

  4. 选择响应类型,然后选择编辑。在本次演练中,我们将以缺少身份验证令牌为例。

  5. 您可以更改 API Gateway 生成的状态代码,以返回满足您的 API 要求的不同状态代码。在此示例中,自定义会将状态代码从默认值 (403) 更改为 404,因为在客户端调用可被视为未找到的不受支持或无效的资源时,会出现此错误消息。

  6. 要返回自定义标头,请选择响应标头下的添加响应标头。为方便说明,我们将添加以下自定义标头:

    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 标头。

  7. 响应模板下,将 application/json 保留为内容类型,然后在模板正文编辑器中输入以下正文映射模板:

    { "message":"$context.error.messageString", "type": "$context.error.responseType", "statusCode": "'404'", "stage": "$context.stage", "resourcePath": "$context.resourcePath", "stageVariables.a": "$stageVariables.a" }

    此示例显示了如何将 $context$stageVariables 属性映射到网关响应正文的属性。

  8. 选择保存更改

  9. 将 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