

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 API Gateway 主控台設定 REST API 的閘道回應
<a name="set-up-gateway-response-using-the-console"></a>

下列範例顯示如何使用 API Gateway 主控台設定 REST API 的閘道回應 

**使用 API Gateway 主控台自訂閘道回應**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇 REST API。

1. 在主導覽窗格中，選擇**閘道資源**。

1. 選擇回應類型，然後選擇**編輯**。在此逐步說明中，我們使用**遺漏身分驗證權杖**作為範例。

1. 您可以變更 API Gateway 所產生的**狀態碼**，以傳回符合您的 API 需求的不同狀態碼。在此範例中，自訂會將狀態碼從預設值 (`403`) 變更為 `404`，因為當用戶端呼叫可視為找不到的不支援或無效資源時會出現此錯誤訊息。

1. 若要傳回自訂標頭，請在**回應標頭**下，選擇**新增標頭**。為了方便說明，我們新增下列自訂標頭：

   ```
   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` 標頭以允許 API 的 CORS 存取；`x-amzn-RequestId` 的輸入請求標頭會對應到回應中的 `request-id`；傳入請求的 `petId` 路徑變數會對應到回應中的 `request-path` 標頭；而原始請求的 `q` 查詢參數會對應到回應的 `request-query` 標頭。

1. 在**回應範本**下，將**內容類型**保持為 `application/json`，然後在**範本內文**編輯器中輸入下列內文對應範本：

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

   此範例示範如何將 `$context` 與 `$stageVariables` 屬性對應到閘道回應內文的屬性。

1. 選擇**儲存變更**。

1. 將 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 後端是[寵物店](http://petstore-demo-endpoint.execute-api.com/petstore/pets)，而且 API 已定義階段變數 `a`。