

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

# 覆寫 API Gateway 中 REST API 的 API 請求和回應參數及狀態碼
<a name="apigateway-override-request-response-parameters"></a>

您可以使用映射範本轉換來覆寫任何類型的請求參數、回應標頭或回應狀態碼。使用映射範本執行下列操作：
+ 執行多對一參數映射
+ 在套用標準 API Gateway 映射之後覆寫參數
+ 根據內文內容或其他參數值，有條件地映射參數
+ 以程式設計方式建立新參數
+ 覆寫由您的整合端點所傳回的狀態碼

覆寫是最終。覆寫只能套用到每個參數一次。如果您嘗試覆寫相同的參數多次，API Gateway 會傳回 `5XX` 回應。如果您必須多次在整個範本中覆寫相同的參數，我們建議您建立變數與在範本結尾套用覆寫。只會在整個範本剖析後才套用範本。

## 範例 1：根據整合內文覆寫狀態碼
<a name="apigateway-override-request-response-examples"></a>

下列範例使用[範例 API](api-gateway-create-api-from-example.md)，根據整合回應內文覆寫狀態碼。

------
#### [ AWS 管理主控台 ]

**根據整合回應內文覆寫狀態碼**

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

1. 選擇 **Create API (建立 API)**。

1. 針對 **REST API**，選擇**組建**。

1. 針對 **API 詳細資訊**，選擇**範例 API**。

1. 選擇**建立 API**。

   API Gateway 會建立範例寵物商店 API。若要擷取有關寵物的資訊，您可以使用 API 方法請求 `GET /pets/{petId}`，其中 `{petId}` 是對應寵物 ID 號碼的路徑參數。

   在此範例中，您會在偵測到錯誤條件時，將 `GET` 方法的回應程式碼覆寫為 `400`。

1. 在**資源**樹狀結構中的 `/{petId}` 下，選擇 `GET` 方法。

1. 首先，測試目前的 API 實作。

   選擇**測試**標籤。您可能需要選擇向右箭頭按鈕才能顯示此索引標籤。

1. 針對 **petId**，輸入 **-1**，然後選擇**測試**。

   **回應內文**指出超出範圍錯誤：

   ```
   {
     "errors": [
       {
         "key": "GetPetRequest.petId",
         "message": "The value is out of range."
       }
     ]
   }
   ```

   此外，**日誌**下的最後一行結尾為：`Method completed with status: 200`。

   整合已成功完成，但發生錯誤。現在您將根據整合回應覆寫狀態碼。

1. 在**整合回應**索引標籤上，針對**預設 - 回應**，選擇**編輯**。

1. 選擇**對應範本**。

1. 選擇**新增對應範本**。

1. 針對**內容類型**，輸入 **application/json**。

1. 針對**範本內文**，輸入下列內容：

   ```
   #set($inputRoot = $input.path('$'))
   $input.json("$")
   #if($inputRoot.toString().contains("error"))
   #set($context.responseOverride.status = 400)
   #end
   ```

   如果整合回應包含字串 `error`，則此映射範本會使用 `$context.responseOverride.status` 變數將狀態碼覆寫為 `400`。

1. 選擇**儲存**。

1. 選擇**測試**標籤。

1. 針對 **petId**，輸入 **-1**。

1. 在結果中，**Response Body (回應內文)** 表示超出範圍錯誤：

   ```
   {
     "errors": [
       {
         "key": "GetPetRequest.petId",
         "message": "The value is out of range."
       }
     ]
   }
   ```

   然而，**日誌**下的最後一列結尾現在會是：`Method completed with status: 400`。

------
#### [ CloudFormation ]

 在此範例中，您使用 [body](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 屬性將 OpenAPI 定義檔案匯入 API Gateway 中。

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body: 
        openapi: 3.0.1
        info:
          title: PetStore Example 1
          description: Example pet store API.
          version: "2025-01-14T00:13:18Z"
        paths:
          /pets/{petId}:
            get:
              parameters:
                - name: petId
                  in: path
                  required: true
                  schema:
                    type: string
              responses:
                "200":
                  description: 200 response
              x-amazon-apigateway-integration:
                httpMethod: GET
                uri: http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets/{petId}
                responses:
                  default:
                    statusCode: "200"
                    responseTemplates:
                      application/json: |-
                        #set($inputRoot = $input.path('$'))
                        $input.json("$")
                        #if($inputRoot.toString().contains("error"))
                        #set($context.responseOverride.status = 400)
                        #end
                requestParameters:
                  integration.request.path.petId: method.request.path.petId
                passthroughBehavior: when_no_match
                type: http
        components:
          schemas:
            Pet:
              type: object
              properties:
                id:
                  type: integer
                type:
                  type: string
                price:
                  type: number
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

以下 OpenAPI 定義會建立 `GET pets/{petId}` 資源，並根據整合內文覆寫狀態碼。

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "PetStore Example 1",
    "description" : "Example pet store API.",
    "version" : "2025-01-14T00:13:18Z"
  },
  "paths" : {
    "/pets/{petId}" : {
      "get" : {
        "parameters" : [ {
          "name" : "petId",
          "in" : "path",
          "required" : true,
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response"
          }
        },
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets/{petId}",
          "responses" : {
            "default" : {
              "statusCode" : "200",
              "responseTemplates" : {
                "application/json" : "#set($inputRoot = $input.path('$'))\n$input.json(\"$\")\n#if($inputRoot.toString().contains(\"error\"))\n#set($context.responseOverride.status = 400)\n#end"
              }
            }
          },
          "requestParameters" : {
            "integration.request.path.petId" : "method.request.path.petId"
          },
          "passthroughBehavior" : "when_no_match",
          "type" : "http"
        }
      }
    }
  },
  "components" : {
    "schemas" : {
      "Pet" : {
        "type" : "object",
        "properties" : {
          "id" : {
            "type" : "integer"
          },
          "type" : {
            "type" : "string"
          },
          "price" : {
            "type" : "number"
          }
        }
      }
    }
  }
}
```

------

## 範例 2：覆寫請求標頭並建立新標頭
<a name="apigateway-override-request-response-examples-2"></a>

下列範例使用[範例 API](api-gateway-create-api-from-example.md) 覆寫請求標頭並建立新標頭。

------
#### [ AWS 管理主控台 ]

**透過建立新標頭來覆寫方法的請求標頭**

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

1. 選擇您在上述教學課程中建立的範例 API。API 的名稱應為 **PetStore**。

1. 在**資源**樹狀結構中的 `/pet` 下，選擇 `GET` 方法。

1. 在**方法請求**索引標籤上，針對**方法請求設定**，選擇**編輯**。

1. 選擇 **HTTP 請求標頭**，然後選擇**新增標頭**。

1. 對於**名稱**，輸入 **header1**。

1. 選擇**新增標頭**，然後建立名為 **header2** 的第二個標頭。

1. 選擇**儲存**。

   現在，請使用映射範本將這些標頭合併成一個標頭值。

1. 在**整合請求**索引標籤上，針對**整合請求設定**，選擇**編輯**。

1. 針對**請求內文傳遞**，選取**未定義範本時 (建議)**。

1. 選擇**對應範本**，然後執行下列動作：

   1. 選擇**新增映射範本**。

   1. 針對**內容類型**，輸入 **application/json**。

   1. 針對**範本內文**，輸入下列內容：

      ```
      #set($header1Override = "pets")
      #set($header3Value = "$input.params('header1')$input.params('header2')")
      $input.json("$")
      #set($context.requestOverride.header.header3 = $header3Value)
      #set($context.requestOverride.header.header1 = $header1Override)
      #set($context.requestOverride.header.multivalueheader=[$header1Override, $header3Value])
      ```

      此映射範本會將 `header1` 覆寫為字串 `pets`，並建立結合 `header1` 和 `header2` 且名為 `$header3Value` 的多值標頭。

1. 選擇**儲存**。

1. 選擇**測試**標籤。

1. 在**標頭**下，複製下列程式碼：

   ```
   header1:header1Val
   header2:header2Val
   ```

1. 選擇 **Test (測試)**。

   在**日誌**中，您應該會看到包括此文字的項目：

   ```
   Endpoint request headers: {header3=header1Valheader2Val, 
   header2=header2Val, header1=pets, x-amzn-apigateway-api-id=api-id,
   Accept=application/json, multivalueheader=pets,header1Valheader2Val}
   ```

------
#### [ CloudFormation ]

 在此範例中，您使用 [body](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 屬性將 OpenAPI 定義檔案匯入 API Gateway 中。

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body: 
        openapi: 3.0.1
        info:
          title: PetStore Example 2
          description: Example pet store API.
          version: "2025-01-14T00:36:18Z"
        paths:
          /pets:
            get:
              parameters:
                - name: header2
                  in: header
                  schema:
                    type: string
                - name: page
                  in: query
                  schema:
                    type: string
                - name: type
                  in: query
                  schema:
                    type: string
                - name: header1
                  in: header
                  schema:
                    type: string
              responses:
                "200":
                  description: 200 response
              x-amazon-apigateway-integration:
                httpMethod: GET
                uri: http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets
                responses:
                  default:
                    statusCode: "200"
                requestParameters:
                  integration.request.header.header1: method.request.header.header1
                  integration.request.header.header2: method.request.header.header2
                  integration.request.querystring.page: method.request.querystring.page
                  integration.request.querystring.type: method.request.querystring.type
                requestTemplates:
                  application/json: |-
                    #set($header1Override = "pets")
                    #set($header3Value = "$input.params('header1')$input.params('header2')")
                    $input.json("$")
                    #set($context.requestOverride.header.header3 = $header3Value)
                    #set($context.requestOverride.header.header1 = $header1Override)
                    #set($context.requestOverride.header.multivalueheader=[$header1Override, $header3Value])
                passthroughBehavior: when_no_match
                type: http
        components:
          schemas:
            Pet:
              type: object
              properties:
                id:
                  type: integer
                type:
                  type: string
                price:
                  type: number
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

 以下 OpenAPI 定義會建立 `GET pets` 資源，以及覆寫請求標頭並建立新標頭。

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "PetStore Example 2",
    "description" : "Example pet store API.",
    "version" : "2025-01-14T00:36:18Z"
  },
  "paths" : {
    "/pets" : {
      "get" : {
        "parameters" : [ {
          "name" : "header2",
          "in" : "header",
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "page",
          "in" : "query",
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "type",
          "in" : "query",
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "header1",
          "in" : "header",
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response"
          }
        },
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.header.header1" : "method.request.header.header1",
            "integration.request.header.header2" : "method.request.header.header2",
            "integration.request.querystring.page" : "method.request.querystring.page",
            "integration.request.querystring.type" : "method.request.querystring.type"
          },
          "requestTemplates" : {
            "application/json" : "#set($header1Override = \"pets\")\n#set($header3Value = \"$input.params('header1')$input.params('header2')\")\n$input.json(\"$\")\n#set($context.requestOverride.header.header3 = $header3Value)\n#set($context.requestOverride.header.header1 = $header1Override)\n#set($context.requestOverride.header.multivalueheader=[$header1Override, $header3Value])"
          },
          "passthroughBehavior" : "when_no_match",
          "type" : "http"
        }
      }
    }
  }
}
```

------

若要使用映射範本覆寫，請新增一或多個下列 `$context` 變數。如需 `$context` 變數清單，請參閱 [資料轉換的內容變數](api-gateway-mapping-template-reference.md#context-variable-reference)。