

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

# API Gateway 中 REST API 的二進位媒體類型
<a name="api-gateway-payload-encodings"></a>

在 API Gateway 中，API 請求與回應可以有文字或二進位承載。文字承載是 `UTF-8` 編碼的 JSON 字串。二進位承載是文字承載以外的任何項目。例如，二進位承載可以是 JPEG 檔案、GZip 檔案或 XML 檔案。支援二進位媒體所需的 API 組態取決於您的 API 是否使用代理或非代理整合。

如果您使用代理整合與承載回應串流，則不需要設定二進位媒體類型。如需詳細資訊，請參閱[在 API Gateway 中串流代理整合的整合回應](response-transfer-mode.md)。

## AWS Lambda 代理整合
<a name="api-gateway-payload-encodings-proxy"></a>

若要處理 AWS Lambda 代理整合的二進位承載，您必須對函數的回應進行 base64 編碼。您也必須為 API 配置 [binaryMediaTypes](https://docs.aws.amazon.com/apigateway/latest/api/API_RestApi.html#apigw-Type-RestApi-binaryMediaTypes)。您的 API `binaryMediaTypes` 組態是 API 視為二進位資料的內容類型列表。範例二進位媒體類型包括 `image/png` 或 `application/octet-stream`。您可以使用萬用字元 (`*`) 來涵蓋多種媒體類型。

API Gateway 會使用來自用戶端的第一個 `Accept` 標頭來判斷回應是否應該傳回二進位媒體。若要在無法控制 `Accept` 標頭值的順序 (例如來自瀏覽器的請求) 時傳回二進位媒體，請將 API 的二進位媒體類型設定為 `*/*`。

如需範例程式碼，請參閱 [在 API Gateway 中從 Lambda 代理整合傳回二進位媒體](lambda-proxy-binary-media.md)。

如果您使用 Lambda 代理整合與承載回應串流，則不需要設定二進位媒體類型。如需詳細資訊，請參閱[在 API Gateway 中設定 Lambda 代理整合與承載回應串流](response-transfer-mode-lambda.md)。

## 非代理伺服器整合
<a name="api-gateway-payload-encodings-non-proxy"></a>

若要處理非代理整合的二進位承載，您可以將媒體類型新增至 `RestApi` 資源的 [binaryMediaTypes](https://docs.aws.amazon.com/apigateway/latest/api/API_RestApi.html#apigw-Type-RestApi-binaryMediaTypes) 清單。您的 API `binaryMediaTypes` 組態是 API 視為二進位資料的內容類型列表。或者，您可以在 [Integration](https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html) 與 [IntegrationResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_IntegrationResponse.html) 資源上設定 [contentHandling](https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html#contentHandling) 屬性。`contentHandling` 值可以是 `CONVERT_TO_BINARY`、`CONVERT_TO_TEXT` 或未定義。

**注意**  
若是 `MOCK` 或私有整合，不支援在 AWS 管理主控台中設定 `contentHandling` 屬性。您必須使用 AWS CLI CloudFormation、 或 SDK 來設定`contentHandling`屬性。

根據 `contentHandling` 值，以及回應的 `Content-Type` 標頭或傳入請求的 `Accept` 標頭是否符合 `binaryMediaTypes` 清單中的項目，API Gateway 可以將原始二進位位元組編碼為 Base64 編碼字串、將 Base64 編碼字串解碼回其原始位元組，或傳遞本文而不進行任何修改。

您必須遵循下列方式設定 API，以在 API Gateway 中支援 API 的二進位承載：
+ 將所需的二進位媒體類型新增至 [RestApi](https://docs.aws.amazon.com/apigateway/latest/api/API_RestApi.html) 資源上的 `binaryMediaTypes` 清單。如果未定義此屬性與 `contentHandling` 屬性，則會將承載當作 UTF-8 編碼的 JSON 字串來處理。
+ 將 [Integration](https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html) 資源的 `contentHandling` 屬性定址。
  + 若要讓請求承載從 base64 編碼的字串轉換為其二進位 Blob，請將屬性設定為 `CONVERT_TO_BINARY`。
  + 若要將請求承載從二進位 Blob 轉換為 base64 編碼的字串，請將屬性設定為 `CONVERT_TO_TEXT`。
  + 若要在不修改的情況下傳遞承載，請將屬性保留為未定義。若要在未經修改的情況下傳遞二進位承載，您也必須確定 `Content-Type` 符合其中一個 `binaryMediaTypes` 項目，並且已針對 API 啟用[傳遞行為](integration-passthrough-behaviors.md)。
+ 設定 [IntegrationResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_IntegrationResponse.html) 資源的 `contentHandling` 屬性。`contentHandling` 屬性、用戶端請求中的 `Accept` 標頭，以及 API 的 `binaryMediaTypes` 組合會決定 API Gateway 處理內容類型轉換的方式。如需詳細資訊，請參閱[API Gateway 中的內容類型轉換](api-gateway-payload-encodings-workflow.md)。

**重要**  
當請求的 `Accept` 標頭中包含多個媒體類型時，API Gateway 只會採用第一個 `Accept` 媒體類型。如果您無法控制 `Accept` 媒體類型的順序，而且二進位內容的媒體類型不是清單中的第一個類型，您可以在 API 的 `binaryMediaTypes` 清單中新增第一個 `Accept` 媒體類型。API Gateway 將以二進位處理此清單中的所有內容類型。  
例如，若要在瀏覽器中使用 `<img>` 元素來傳送 JPEG 檔案，瀏覽器可能會在請求中傳送 `Accept:image/webp,image/*,*/*;q=0.8`。透過將 `image/webp` 新增至 `binaryMediaTypes` 清單，端點就能收到二進位格式的 JPEG 檔案。

如需 API Gateway 如何處理文字和二進位承載的詳細資訊，請參閱[API Gateway 中的內容類型轉換](api-gateway-payload-encodings-workflow.md)。

# API Gateway 中的內容類型轉換
<a name="api-gateway-payload-encodings-workflow"></a>

 您的 API 的 `binaryMediaTypes`、用戶端請求中的標頭，以及整合 `contentHandling` 屬性的組合將決定 API Gateway 編碼有效承載的方式。

下表顯示 API Gateway 如何轉換請求的 `Content-Type` 標頭、[RestApi](https://docs.aws.amazon.com/apigateway/latest/api/API_RestApi.html) 資源的 `binaryMediaTypes` 清單與 [Integration](https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html) 資源的 `contentHandling` 屬性值之特定組態的請求酬載。


| 方法請求承載 | 請求 `Content-Type` 標頭 | `binaryMediaTypes` | `contentHandling` | 整合請求承載 | 
| --- | --- | --- | --- | --- | 
| 文字資料 | 任何資料類型 | 未定義 | 未定義 | UTF8 編碼字串 | 
| 文字資料 | 任何資料類型 | 未定義 | CONVERT\$1TO\$1BINARY | Base64 解碼的二進位 Blob | 
| 文字資料 | 任何資料類型 | 未定義 | CONVERT\$1TO\$1TEXT | UTF8 編碼字串 | 
| 文字資料 | 文字資料類型 | 設定相符媒體類型 | 未定義 | 文字資料 | 
| 文字資料 | 文字資料類型 | 設定相符媒體類型 | CONVERT\$1TO\$1BINARY | Base64 解碼的二進位 Blob | 
| 文字資料 | 文字資料類型 | 設定相符媒體類型 | CONVERT\$1TO\$1TEXT | 文字資料 | 
| 二進位資料 | 二進位資料類型 | 設定相符媒體類型 | 未定義 | 二進位資料 | 
| 二進位資料 | 二進位資料類型 | 設定相符媒體類型 | CONVERT\$1TO\$1BINARY | 二進位資料 | 
| 二進位資料 | 二進位資料類型 | 設定相符媒體類型 | CONVERT\$1TO\$1TEXT | Base64 編碼字串 | 

下表顯示 API Gateway 如何轉換請求的 `Accept` 標頭、[RestApi](https://docs.aws.amazon.com/apigateway/latest/api/API_RestApi.html) 資源的 `binaryMediaTypes` 清單與 [IntegrationResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_IntegrationResponse.html) 資源的 `contentHandling` 屬性值之特定組態的回應酬載。

**重要**  
 當請求的 `Accept` 標頭中包含多個媒體類型時，API Gateway 只會採用第一個 `Accept` 媒體類型。如果您無法控制 `Accept` 媒體類型的順序，而且二進位內容的媒體類型不是清單中的第一個類型，您可以在 API 的 `binaryMediaTypes` 清單中新增第一個 `Accept` 媒體類型。API Gateway 將以二進位處理此清單中的所有內容類型。  
例如，若要在瀏覽器中使用 `<img>` 元素來傳送 JPEG 檔案，瀏覽器可能會在請求中傳送 `Accept:image/webp,image/*,*/*;q=0.8`。透過將 `image/webp` 新增至 `binaryMediaTypes` 清單，端點就能收到二進位格式的 JPEG 檔案。


| 整合回應承載 | 請求 `Accept` 標頭 | `binaryMediaTypes` | `contentHandling` | 方法回應承載 | 
| --- | --- | --- | --- | --- | 
| 文字或二進位資料 | 文字類型 | 未定義 | 未定義 | UTF8 編碼字串 | 
| 文字或二進位資料 | 文字類型 | 未定義 | CONVERT\$1TO\$1BINARY | Base64 解碼的 Blob | 
| 文字或二進位資料 | 文字類型 | 未定義 | CONVERT\$1TO\$1TEXT | UTF8 編碼字串 | 
| 文字資料 | 文字類型 | 設定相符媒體類型 | 未定義 | 文字資料 | 
| 文字資料 | 文字類型 | 設定相符媒體類型 | CONVERT\$1TO\$1BINARY | Base64 解碼的 Blob | 
| 文字資料 | 文字類型 | 設定相符媒體類型 | CONVERT\$1TO\$1TEXT | UTF8 編碼字串 | 
| 文字資料 | 二進位類型 | 設定相符媒體類型 | 未定義 | Base64 解碼的 Blob | 
| 文字資料 | 二進位類型 | 設定相符媒體類型 | CONVERT\$1TO\$1BINARY | Base64 解碼的 Blob | 
| 文字資料 | 二進位類型 | 設定相符媒體類型 | CONVERT\$1TO\$1TEXT | UTF8 編碼字串 | 
| 二進位資料 | 文字類型 | 設定相符媒體類型 | 未定義 | Base64 編碼字串 | 
| 二進位資料 | 文字類型 | 設定相符媒體類型 | CONVERT\$1TO\$1BINARY | 二進位資料 | 
| 二進位資料 | 文字類型 | 設定相符媒體類型 | CONVERT\$1TO\$1TEXT | Base64 編碼字串 | 
| 二進位資料 | 二進位類型 | 設定相符媒體類型 | 未定義 | 二進位資料 | 
| 二進位資料 | 二進位類型 | 設定相符媒體類型 | CONVERT\$1TO\$1BINARY | 二進位資料 | 
| 二進位資料 | 二進位類型 | 設定相符媒體類型 | CONVERT\$1TO\$1TEXT | Base64 編碼字串 | 

將文字承載轉換成二進位 Blob 時，API Gateway 會假設文字資料是 Base64 編碼字串，並將二進位資料輸出為 Base64 解碼的 Blob。如果轉換失敗，它會傳回 `500` 回應，表示 API 組態錯誤。您不會為這類轉換提供對應範本，但您必須在 API 上啟用[傳遞行為](integration-passthrough-behaviors.md)。

將二進位承載轉換成文字字串時，API Gateway 一律會在二進位資料上套用 Base64 編碼。您可以為這類承載定義對應範本，但只能透過 `$input.body` 存取對應範本中的 Base64 編碼字串，如下列範例對應範本摘要所示。

```
{   
    "data": "$input.body"
}
```

若要傳遞二進位承載而不進行任何修改，您必須在 API 上啟用[傳遞行為](integration-passthrough-behaviors.md)。

# 使用 API Gateway 主控台啟用二進位支援
<a name="api-gateway-payload-encodings-configure-with-console"></a>

本節說明如何使用 API Gateway 主控台來啟用二進位支援。舉例來說，我們使用與 Amazon S3 整合的 API。我們將重點放在設定支援的媒體類型，以及指定應該如何處理承載的作業上。如需如何建立與 Amazon S3 整合之 API 的詳細資訊，請參閱[教學：建立 REST API 做為 Amazon S3 代理](integrating-api-with-aws-services-s3.md)。

**使用 API Gateway 主控台啟用二進位支援**

1. 設定 API 的二進位媒體類型：

   1. 建立新的 API 或選擇現有的 API。在此範例中，我們將 API 命名為 `FileMan`。

   1. 在主導覽面板中所選取的 API 下，選擇 **API 設定**。

   1. 在 **API 設定**窗格的**二進位媒體類型**區段中，選擇**管理媒體類型**。

   1. 選擇**新增二進位媒體類型**。

   1. 在輸入文字欄位中，輸入必要的媒體類型，例如 **image/png**。如果需要，請重複此步驟來新增更多媒體類型。若要支援所有二進位媒體類型，請指定 `*/*`。

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

1. 設定如何處理 API 方法的訊息承載：

   1. 在 API 中建立新的資源或選擇現有的資源。在此範例中，我們使用 `/{folder}/{item}` 資源。

   1. 在資源上建立新的方法或選擇現有的方法。舉例來說，我們使用與 Amazon S3 中 `GET /{folder}/{item}` 動作整合的 `Object GET` 方法。

   1. 針對**內容處理**，選擇一個選項。

         
![\[在 API Gateway 主控台中設定 GET 方法。\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/binary-support-content-handling-on-method-new-console.png)

      如果您不想要在用戶端與後端接受相同的二進位格式時轉換本文，請選擇**傳遞**。例如，當後端需要二進位請求承載以 JSON 屬性傳入時，選擇**轉換為文字**，以將二進位本文轉換成 Base64 編碼字串。此外，當用戶端提交 Base64 編碼字串且後端需要原始二進位格式時，或是當端點傳回 Base64 編碼字串且用戶端只接受二進位輸出時，選擇**轉換為二進位**。

   1. 針對**請求內文傳遞**，選擇**未定義範本時 (建議)**以在請求內文上啟用傳遞行為。

      您也可以選擇**永不**。這意味著 API 將拒絕 content-types 沒有對應範本的資料。

   1. 在整合請求中保留傳入請求的 `Accept` 標頭。如果您將 `contentHandling` 設定為 `passthrough` 並想要在執行階段覆寫該設定，則應該這麼做。

         
![\[在整合請求中保留 Accept 標頭。\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/binary-support-preserve-incoming-accept-header-new-console.png)

   1. 若要轉換成文字，請定義對應範本，將 Base64 編碼的二進位資料設為必要的格式。

      以下是要轉換為文字的對應範本範例：

      ```
      {
        "operation": "thumbnail",
        "base64Image": "$input.body"
      }
      ```

      此對應範本的格式取決於輸入的端點需求。

   1. 選擇**儲存**。

# 使用 API Gateway REST API 啟用二進位支援
<a name="api-gateway-payload-encodings-configure-with-control-service-api"></a>

下列作業示範如何使用 API Gateway REST API 呼叫來啟用二進位支援。

**Topics**
+ [將支援的二進位媒體類型新增與更新至 API](#api-gateway-payload-encodings-setup-with-api-set-encodings-map)
+ [設定請求承載轉換](#api-gateway-payload-encodings-setup-with-api-set-integration-request-encoding)
+ [設定回應承載轉換](#api-gateway-payload-encodings-setup-with-api-set-integration-response-encoding)
+ [將二進位資料轉換成文字資料](#api-gateway-payload-encodings-convert-binary-to-string)
+ [將文字資料轉換成二進位承載](#api-gateway-payload-encodings-convert-string-to-binary)
+ [傳遞二進位承載](#api-gateway-payload-encodings-pass-binary-as-is)

## 將支援的二進位媒體類型新增與更新至 API
<a name="api-gateway-payload-encodings-setup-with-api-set-encodings-map"></a>

若要讓 API Gateway 支援新的二進位媒體類型，您必須將二進位媒體類型新增至 `RestApi` 資源的 `binaryMediaTypes` 清單。例如，若要讓 API Gateway 處理 JPEG 影像，請將 `RestApi` 請求提交至 `PATCH` 資源：

```
PATCH /restapis/<restapi_id>

{
  "patchOperations" : [ {
    "op" : "add",
    "path" : "/binaryMediaTypes/image~1jpeg"
  } 
 ]
}
```

`image/jpeg` 的 MIME 類型規格是 `path` 屬性值的一部分，因此會逸出為 `image~1jpeg`。

若要更新支援的二進位媒體類型，請從 `binaryMediaTypes` 資源的 `RestApi` 清單中取代或移除媒體類型。例如，若要將二進位支援從 JPEG 檔案變更為原始位元組，請對 `PATCH` 資源提交 `RestApi` 請求，如下所示。

```
PATCH /restapis/<restapi_id>

{
  "patchOperations" : [{
    "op" : "replace",
    "path" : "/binaryMediaTypes/image~1jpeg",
    "value" : "application/octet-stream"
  },
  {
    "op" : "remove",
    "path" : "/binaryMediaTypes/image~1jpeg"
  }]
}
```

## 設定請求承載轉換
<a name="api-gateway-payload-encodings-setup-with-api-set-integration-request-encoding"></a>

如果端點需要二進位輸入，請將 `contentHandling` 資源的 `Integration` 屬性設定為 `CONVERT_TO_BINARY`。若要執行這項操作，請提交 `PATCH` 請求，如下所示：

```
PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/integration

{
  "patchOperations" : [ {
    "op" : "replace",
    "path" : "/contentHandling",
    "value" : "CONVERT_TO_BINARY"
  }]
}
```

## 設定回應承載轉換
<a name="api-gateway-payload-encodings-setup-with-api-set-integration-response-encoding"></a>

如果用戶端接受二進位 Blob 格式的結果，而不是從端點傳回的 Base64 編碼承載，將 `IntegrationResponse` 資源的 `contentHandling` 屬性設定為 `CONVERT_TO_BINARY`。若要這樣做，請提交 `PATCH` 請求，如下所示：

```
PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/integration/responses/<status_code>

{
  "patchOperations" : [ {
    "op" : "replace",
    "path" : "/contentHandling",
    "value" : "CONVERT_TO_BINARY"
  }]
}
```

## 將二進位資料轉換成文字資料
<a name="api-gateway-payload-encodings-convert-binary-to-string"></a>

若要透過 API Gateway 將二進位資料做為輸入 AWS Lambda 或 Kinesis 的 JSON 屬性傳送，請執行下列動作：

1. 將 `application/octet-stream` 的新二進位媒體類型新增至 API 的 `binaryMediaTypes` 清單，以啟用 API 的二進位承載支援。

   ```
   PATCH /restapis/<restapi_id>
   
   {
     "patchOperations" : [ {
       "op" : "add",
       "path" : "/binaryMediaTypes/application~1octet-stream"
     } 
    ]
   }
   ```

1. 在 `CONVERT_TO_TEXT` 資源的 `contentHandling` 屬性上設定 `Integration`，並提供對應範本，以將二進位資料的 Base64 編碼字串指派給 JSON 屬性。在下列範例中，JSON 屬性是持有 Base64 編碼字串的 `body` 與 `$input.body`。

   ```
   PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/integration
   
   {
     "patchOperations" : [
       {
         "op" : "replace",
         "path" : "/contentHandling",
         "value" : "CONVERT_TO_TEXT"
       },
       {
         "op" : "add",
         "path" : "/requestTemplates/application~1octet-stream",
         "value" : "{\"body\": \"$input.body\"}"
       }
     ]
   }
   ```

## 將文字資料轉換成二進位承載
<a name="api-gateway-payload-encodings-convert-string-to-binary"></a>

假設 Lambda 函數會傳回 Base64 編碼字串格式的影像檔。若要透過 API Gateway 將此二進位輸出傳遞給用戶端，請執行下列操作：

1. 新增 `binaryMediaTypes` 的二進位媒體類型 (如果尚未在清單中)，以更新 API 的 `application/octet-stream` 清單。

   ```
   PATCH /restapis/<restapi_id>
   
   {
     "patchOperations" : [ {
       "op" : "add",
       "path" : "/binaryMediaTypes/application~1octet-stream",
     }]
   }
   ```

1.  將 `contentHandling` 資源上的 `Integration` 屬性設定為 `CONVERT_TO_BINARY`。請勿定義對應範本。如果您未定義映射範本，API Gateway 可呼叫傳遞範本，將 Base64 解碼的二進位 Blob 做為影像檔傳回至用戶端。

   ```
   PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/integration/responses/<status_code>
   
   {
     "patchOperations" : [
       {
         "op" : "replace",
         "path" : "/contentHandling",
         "value" : "CONVERT_TO_BINARY"
       }
     ]
   }
   ```

## 傳遞二進位承載
<a name="api-gateway-payload-encodings-pass-binary-as-is"></a>

 若要使用 API Gateway 將映像儲存在 Amazon S3 儲存貯體中，請執行下列動作：

1. 新增 `binaryMediaTypes` 的二進位媒體類型 (如果尚未在清單中)，以更新 API 的 `application/octet-stream` 清單。

   ```
   PATCH /restapis/<restapi_id>
   
   {
     "patchOperations" : [ {
       "op" : "add",
       "path" : "/binaryMediaTypes/application~1octet-stream"
     }
    ]
   }
   ```

1. 在 `contentHandling` 資源的 `Integration` 屬性上設定 `CONVERT_TO_BINARY`。將 `WHEN_NO_MATCH` 設定為 `passthroughBehavior` 屬性值，而不需要定義對應範本。這可讓 API Gateway 叫用傳遞範本。

   ```
   PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/integration
   
   {
     "patchOperations" : [
       {
         "op" : "replace",
         "path" : "/contentHandling",
         "value" : "CONVERT_TO_BINARY"
       },
       {
         "op" : "replace",
         "path" : "/passthroughBehaviors",
         "value" : "WHEN_NO_MATCH"
       }
     ]
   }
   ```

# API Gateway 的匯入與匯出內容編碼
<a name="api-gateway-payload-encodings-import-and-export"></a>

 若要匯入 [RestApi](https://docs.aws.amazon.com/apigateway/latest/api/API_RestApi.html) 上的 `binaryMediaTypes` 清單，請使用 API OpenAPI 定義檔的下列 API Gateway 延伸。此延伸也可用來匯出 API 設定。
+ [x-amazon-apigateway-binary-media-types 屬性](api-gateway-swagger-extensions-binary-media-types.md)

若要匯入與匯出 `Integration` 或 `IntegrationResponse` 資源上的 `contentHandling` 屬性值，請使用 OpenAPI 定義的下列 API Gateway 延伸：
+ [x-amazon-apigateway-integration 物件](api-gateway-swagger-extensions-integration.md)
+ [x-amazon-apigateway-integration.response 物件](api-gateway-swagger-extensions-integration-response.md)

# 在 API Gateway 中從 Lambda 代理整合傳回二進位媒體
<a name="lambda-proxy-binary-media"></a>

要從 [AWS Lambda 代理整合](set-up-lambda-proxy-integrations.md)傳回二進位媒體，您需要對 Lambda 函數的回應進行 base64 編碼。您還必須[配置 API 的二進位媒體類型](api-gateway-payload-encodings-configure-with-console.md)。當您設定 API 的二進位媒體類型時，API 會將該內容類型視為二進位資料。承載大小上限為 10 MB。

**注意**  
若要使用網頁瀏覽器來叫用具有此範例整合的 API，請將 API 的二進位媒體類型設定為 `*/*`。API Gateway 會使用來自用戶端的第一個 `Accept` 標頭來判斷回應是否應該傳回二進位媒體。若要在無法控制 `Accept` 標頭值的順序 (例如來自瀏覽器的請求) 時傳回二進位媒體，請將 API 的二進位媒體類型設定為 `*/*` (適用於所有內容類型)。

下列範例 Lambda 函數可將二進位映像從 Amazon S3 或文字傳回給用戶端。該函數的回應會包括一個 `Content-Type` 標頭，以指示給用戶端它傳回的資料類型。該函數會有條件地在其回應中設定 `isBase64Encoded` 屬性，具體取決於它傳回的資料類型。

------
#### [ Node.js ]

```
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3"

const client = new S3Client({region: 'us-east-2'});

export const handler = async (event) => {

  var randomint = function(max) {
    return Math.floor(Math.random() * max);
  }
  var number = randomint(2);
  if (number == 1){ 
    const input = {
      "Bucket" : "bucket-name",
      "Key" : "image.png"
      }
    try {
      const command = new GetObjectCommand(input)
      const response = await client.send(command);
      var str = await response.Body.transformToByteArray();
    } catch (err) {
      console.error(err);
    }
    const base64body = Buffer.from(str).toString('base64');
    return {
      'headers': { "Content-Type": "image/png" },
      'statusCode': 200,
      'body': base64body,
      'isBase64Encoded': true
      }
    } else {
        return {
        'headers': { "Content-Type": "text/html" },
        'statusCode': 200,
        'body': "<h1>This is text</h1>",
        }
    }
}
```

------
#### [ Python ]

```
import base64
import boto3
import json
import random

s3 = boto3.client('s3')

def lambda_handler(event, context):
    number = random.randint(0,1)
    if number == 1:
        response = s3.get_object(
            Bucket='bucket-name',
            Key='image.png',
        )
        image = response['Body'].read()
        return {
            'headers': { "Content-Type": "image/png" },
            'statusCode': 200,
            'body': base64.b64encode(image).decode('utf-8'),
            'isBase64Encoded': True
        }
    else:
        return {
            'headers': { "Content-type": "text/html" },
            'statusCode': 200,
            'body': "<h1>This is text</h1>",
        }
```

------

若要進一步了解二進位媒體類型，請參閱[API Gateway 中 REST API 的二進位媒體類型](api-gateway-payload-encodings.md)。

# 透過 API Gateway API 存取 Amazon S3 中的二進位檔案
<a name="api-gateway-content-encodings-examples-image-s3"></a>

下列範例示範如何使用 OpenAPI 檔案來存取 Amazon S3 中的影像、如何從 Amazon S3 下載影像，以及如何將影像上傳至 Amazon S3。

**Topics**
+ [存取 Amazon S3 中影像之範例 API 的 OpenAPI 檔案](#api-gateway-content-encodings-example-image-s3-swagger-file)
+ [從 Amazon S3 下載影像](#api-gateway-content-encodings-example-download-image-from-s3)
+ [將影像上傳至 Amazon S3](#api-gateway-content-encodings-example-upload-image-to-s3)

## 存取 Amazon S3 中影像之範例 API 的 OpenAPI 檔案
<a name="api-gateway-content-encodings-example-image-s3-swagger-file"></a>

下列 OpenAPI 檔案顯示一個範例 API，說明如何從 Amazon S3 下載影像檔，以及如何將影像檔上傳至 Amazon S3。此 API 會公開用於下載及上傳指定影像檔的 `GET /s3?key={file-name}` 與 `PUT /s3?key={file-name}` 方法。`GET` 方法會在「200 OK」回應中，將 Base64 編碼字串格式的影像檔當作 JSON 輸出的一部分傳回，後面接著所提供的映射範本。`PUT` 方法接受原始二進位 Blob 作為輸入，並傳回「200 OK」回應與空的承載。

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

```
{
   "openapi": "3.0.0",
   "info": {
      "version": "2016-10-21T17:26:28Z",
      "title": "ApiName"
   },
   "paths": {
      "/s3": {
         "get": {
            "parameters": [
               {
                  "name": "key",
                  "in": "query",
                  "required": false,
                  "schema": {
                     "type": "string"
                  }
               }
            ],
            "responses": {
               "200": {
                  "description": "200 response",
                  "content": {
                     "application/json": {
                        "schema": {
                           "$ref": "#/components/schemas/Empty"
                        }
                     }
                  }
               },
               "500": {
                  "description": "500 response"
               }
            },
            "x-amazon-apigateway-integration": {
               "credentials": "arn:aws:iam::123456789012:role/binarySupportRole",
               "responses": {
                  "default": {
                     "statusCode": "500"
                  },
                  "2\\d{2}": {
                     "statusCode": "200"
                  }
               },
               "requestParameters": {
                  "integration.request.path.key": "method.request.querystring.key"
               },
               "uri": "arn:aws:apigateway:us-west-2:s3:path/{key}",
               "passthroughBehavior": "when_no_match",
               "httpMethod": "GET",
               "type": "aws"
            }
         },
         "put": {
            "parameters": [
               {
                  "name": "key",
                  "in": "query",
                  "required": false,
                  "schema": {
                     "type": "string"
                  }
               }
            ],
            "responses": {
               "200": {
                  "description": "200 response",
                  "content": {
                     "application/json": {
                        "schema": {
                           "$ref": "#/components/schemas/Empty"
                        }
                     },
                     "application/octet-stream": {
                        "schema": {
                           "$ref": "#/components/schemas/Empty"
                        }
                     }
                  }
               },
               "500": {
                  "description": "500 response"
               }
            },
            "x-amazon-apigateway-integration": {
               "credentials": "arn:aws:iam::123456789012:role/binarySupportRole",
               "responses": {
                  "default": {
                     "statusCode": "500"
                  },
                  "2\\d{2}": {
                     "statusCode": "200"
                  }
               },
               "requestParameters": {
                  "integration.request.path.key": "method.request.querystring.key"
               },
               "uri": "arn:aws:apigateway:us-west-2:s3:path/{key}",
               "passthroughBehavior": "when_no_match",
               "httpMethod": "PUT",
               "type": "aws",
               "contentHandling": "CONVERT_TO_BINARY"
            }
         }
      }
   },
   "x-amazon-apigateway-binary-media-types": [
      "application/octet-stream",
      "image/jpeg"
   ],
   "servers": [
      {
         "url": "https://abcdefghi.execute-api.us-east-1.amazonaws.com/{basePath}",
         "variables": {
            "basePath": {
              "default": "/v1"
            }
         }
      }
   ],
   "components": {
      "schemas": {
         "Empty": {
            "type": "object",
            "title": "Empty Schema"
         }
      }
   }
}
```

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

```
{
  "swagger": "2.0",
  "info": {
    "version": "2016-10-21T17:26:28Z",
    "title": "ApiName"
  },
  "host": "abcdefghi.execute-api.us-east-1.amazonaws.com",
  "basePath": "/v1",
  "schemes": [
    "https"
  ],
  "paths": {
    "/s3": {
      "get": {
        "produces": [
          "application/json"
        ],
        "parameters": [
          {
            "name": "key",
            "in": "query",
            "required": false,
            "type": "string"
          }
        ],
        "responses": {
          "200": {
            "description": "200 response",
            "schema": {
              "$ref": "#/definitions/Empty"
            }
          },
          "500": {
            "description": "500 response"
          }
        },
        "x-amazon-apigateway-integration": {
          "credentials": "arn:aws:iam::123456789012:role/binarySupportRole",
          "responses": {
            "default": {
              "statusCode": "500"
            },
            "2\\d{2}": {
              "statusCode": "200"            }
          },
          "requestParameters": {
            "integration.request.path.key": "method.request.querystring.key"
          },
          "uri": "arn:aws:apigateway:us-west-2:s3:path/{key}",
          "passthroughBehavior": "when_no_match",
          "httpMethod": "GET",
          "type": "aws"
        }
      },
      "put": {
        "produces": [
          "application/json", "application/octet-stream"
        ],
        "parameters": [
          {
            "name": "key",
            "in": "query",
            "required": false,
            "type": "string"
          }
        ],
        "responses": {
          "200": {
            "description": "200 response",
            "schema": {
              "$ref": "#/definitions/Empty"
            }
          },
          "500": {
            "description": "500 response"
          }
        },
        "x-amazon-apigateway-integration": {
          "credentials": "arn:aws:iam::123456789012:role/binarySupportRole",
          "responses": {
            "default": {
              "statusCode": "500"
            },
            "2\\d{2}": {
              "statusCode": "200"
            }
          },
          "requestParameters": {
            "integration.request.path.key": "method.request.querystring.key"
          },
          "uri": "arn:aws:apigateway:us-west-2:s3:path/{key}",
          "passthroughBehavior": "when_no_match",
          "httpMethod": "PUT",
          "type": "aws",
          "contentHandling" : "CONVERT_TO_BINARY"
        }
      }
    }
  },
  "x-amazon-apigateway-binary-media-types" : ["application/octet-stream", "image/jpeg"],
  "definitions": {
    "Empty": {
      "type": "object",
      "title": "Empty Schema"
    }
  }
}
```

------

## 從 Amazon S3 下載影像
<a name="api-gateway-content-encodings-example-download-image-from-s3"></a>

從 Amazon S3 下載二進位 Blob 格式的影像檔 (`image.jpg`)：

```
GET /v1/s3?key=image.jpg HTTP/1.1
Host: abcdefghi.execute-api.us-east-1.amazonaws.com
Content-Type: application/json
Accept: application/octet-stream
```

成功回應如下所示：

```
200 OK HTTP/1.1

[raw bytes]
```

由於 `Accept` 標頭已設定為 `application/octet-stream` 的二進位媒體類型，而且啟用 API 的二進位支援，因此會傳回原始位元組。

或者，若要從 Amazon S3 下載 Base64 編碼字串 (格式化為 JSON 屬性) 格式的影像檔 (`image.jpg`)，請將回應範本新增至 200 整合回應，如下列粗體 OpenAPI 定義區塊所示：

```
        "x-amazon-apigateway-integration": {
          "credentials": "arn:aws:iam::123456789012:role/binarySupportRole",
          "responses": {
            "default": {
              "statusCode": "500"
            },
            "2\\d{2}": {
              "statusCode": "200",
              "responseTemplates": {
                "application/json": "{\n   \"image\": \"$input.body\"\n}"
              }
            }
          },
```

要下載影像檔的請求如下所示：

```
GET /v1/s3?key=image.jpg HTTP/1.1
Host: abcdefghi.execute-api.us-east-1.amazonaws.com
Content-Type: application/json
Accept: application/json
```

成功回應如下所示：

```
200 OK HTTP/1.1

{
  "image": "W3JhdyBieXRlc10="
}
```

## 將影像上傳至 Amazon S3
<a name="api-gateway-content-encodings-example-upload-image-to-s3"></a>

將二進位 Blob 格式的影像檔 (`image.jpg`) 上傳至 Amazon S3：

```
PUT /v1/s3?key=image.jpg HTTP/1.1
Host: abcdefghi.execute-api.us-east-1.amazonaws.com
Content-Type: application/octet-stream
Accept: application/json

[raw bytes]
```

成功回應如下所示：

```
200 OK HTTP/1.1        
```

將 Base64 編碼字串格式的影像檔 (`image.jpg`) 上傳至 Amazon S3：

```
PUT /v1/s3?key=image.jpg HTTP/1.1
Host: abcdefghi.execute-api.us-east-1.amazonaws.com
Content-Type: application/json
Accept: application/json

W3JhdyBieXRlc10=
```

輸入承載必須是 Base64 編碼字串，因為 `Content-Type` 標頭值已設定為 `application/json`。成功回應如下所示：

```
200 OK HTTP/1.1
```

# 使用 API Gateway API 存取 Lambda 中的二進位檔案
<a name="api-gateway-content-encodings-examples-image-lambda"></a>

下列 OpenAPI 範例示範如何 AWS Lambda 透過 API Gateway API 存取 中的二進位檔案。此 API 會公開用於下載及上傳指定影像檔的 `GET /lambda?key={file-name}` 與 `PUT /lambda?key={file-name}` 方法。`GET` 方法會在「200 OK」回應中，將 Base64 編碼字串格式的影像檔當作 JSON 輸出的一部分傳回，後面接著所提供的映射範本。`PUT` 方法接受原始二進位 Blob 作為輸入，並傳回「200 OK」回應與空的承載。

您建立 API 呼叫的 Lambda 函數，而該函數必須傳回具有 `application/json` 的 `Content-Type` 標頭的 base64 編碼字串。

**Topics**
+ [存取 Lambda 中影像之範例 API 的 OpenAPI 檔案](#api-gateway-content-encodings-example-image-lambda-swagger-file)
+ [從 Lambda 下載影像](#api-gateway-content-encodings-example-download-image-from-lambda)
+ [將影像上傳至 Lambda](#api-gateway-content-encodings-example-upload-image-to-lambda)

## 存取 Lambda 中影像之範例 API 的 OpenAPI 檔案
<a name="api-gateway-content-encodings-example-image-lambda-swagger-file"></a>

下列 OpenAPI 檔案顯示一個範例 API，說明如何從 Lambda 下載影像檔，以及如何將影像檔上傳至 Lambda。

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

```
{
   "openapi": "3.0.0",
   "info": {
      "version": "2016-10-21T17:26:28Z",
      "title": "ApiName"
   },
   "paths": {
      "/lambda": {
         "get": {
            "parameters": [
               {
                  "name": "key",
                  "in": "query",
                  "required": false,
                  "schema": {
                     "type": "string"
                  }
               }
            ],
            "responses": {
               "200": {
                  "description": "200 response",
                  "content": {
                     "application/json": {
                        "schema": {
                           "$ref": "#/components/schemas/Empty"
                        }
                     }
                  }
               },
               "500": {
                  "description": "500 response"
               }
            },
            "x-amazon-apigateway-integration": {
               "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:image/invocations",
               "type": "AWS",
               "credentials": "arn:aws:iam::123456789012:role/Lambda",
               "httpMethod": "POST",
               "requestTemplates": {
                  "application/json": "{\n   \"imageKey\": \"$input.params('key')\"\n}"
               },
               "responses": {
                  "default": {
                     "statusCode": "500"
                  },
                  "2\\d{2}": {
                     "statusCode": "200",
                     "responseTemplates": {
                        "application/json": "{\n   \"image\": \"$input.body\"\n}"
                     }
                  }
               }
            }
         },
         "put": {
            "parameters": [
               {
                  "name": "key",
                  "in": "query",
                  "required": false,
                  "schema": {
                     "type": "string"
                  }
               }
            ],
            "responses": {
               "200": {
                  "description": "200 response",
                  "content": {
                     "application/json": {
                        "schema": {
                           "$ref": "#/components/schemas/Empty"
                        }
                     },
                     "application/octet-stream": {
                        "schema": {
                           "$ref": "#/components/schemas/Empty"
                        }
                     }
                  }
               },
               "500": {
                  "description": "500 response"
               }
            },
            "x-amazon-apigateway-integration": {
               "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:image/invocations",
               "type": "AWS",
               "credentials": "arn:aws:iam::123456789012:role/Lambda",
               "httpMethod": "POST",
               "contentHandling": "CONVERT_TO_TEXT",
               "requestTemplates": {
                  "application/json": "{\n   \"imageKey\": \"$input.params('key')\", \"image\": \"$input.body\"\n}"
               },
               "responses": {
                  "default": {
                     "statusCode": "500"
                  },
                  "2\\d{2}": {
                     "statusCode": "200"
                  }
               }
            }
         }
      }
   },
   "x-amazon-apigateway-binary-media-types": [
      "application/octet-stream",
      "image/jpeg"
   ],
   "servers": [
      {
         "url": "https://abcdefghi.execute-api.us-east-1.amazonaws.com/{basePath}",
         "variables": {
            "basePath": {
              "default": "/v1"
            }
         }
      }
   ],
   "components": {
      "schemas": {
         "Empty": {
            "type": "object",
            "title": "Empty Schema"
         }
      }
   }
}
```

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

```
{
  "swagger": "2.0",
  "info": {
    "version": "2016-10-21T17:26:28Z",
    "title": "ApiName"
  },
  "host": "abcdefghi.execute-api.us-east-1.amazonaws.com",
  "basePath": "/v1",
  "schemes": [
    "https"
  ],
  "paths": {
    "/lambda": {
      "get": {
        "produces": [
          "application/json"
        ],
        "parameters": [
          {
            "name": "key",
            "in": "query",
            "required": false,
            "type": "string"
          }
        ],
        "responses": {
          "200": {
            "description": "200 response",
            "schema": {
              "$ref": "#/definitions/Empty"
            }
          },
          "500": {
            "description": "500 response"
          }
        },
        "x-amazon-apigateway-integration": {
          "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:image/invocations",
          "type": "AWS",
          "credentials": "arn:aws:iam::123456789012:role/Lambda",
          "httpMethod": "POST",
          "requestTemplates": {
            "application/json": "{\n   \"imageKey\": \"$input.params('key')\"\n}"
          },
          "responses": {
            "default": {
              "statusCode": "500"
            },
            "2\\d{2}": {
              "statusCode": "200",
              "responseTemplates": {
                "application/json": "{\n   \"image\": \"$input.body\"\n}"
              }
            }
          }
        }
      },
      "put": {
        "produces": [
          "application/json", "application/octet-stream"
        ],
        "parameters": [
          {
            "name": "key",
            "in": "query",
            "required": false,
            "type": "string"
          }
        ],
        "responses": {
          "200": {
            "description": "200 response",
            "schema": {
              "$ref": "#/definitions/Empty"
            }
          },
          "500": {
            "description": "500 response"
          }
        },
        "x-amazon-apigateway-integration": {
          "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:image/invocations",
          "type": "AWS",
          "credentials": "arn:aws:iam::123456789012:role/Lambda",
          "httpMethod": "POST",
          "contentHandling" : "CONVERT_TO_TEXT",
          "requestTemplates": {
            "application/json": "{\n   \"imageKey\": \"$input.params('key')\", \"image\": \"$input.body\"\n}"
          },
          "responses": {
            "default": {
              "statusCode": "500"
            },
            "2\\d{2}": {
              "statusCode": "200"
            }
          }
        }
      }
    }
  },
  "x-amazon-apigateway-binary-media-types" : ["application/octet-stream", "image/jpeg"],
  "definitions": {
    "Empty": {
      "type": "object",
      "title": "Empty Schema"
    }
  }
}
```

------

## 從 Lambda 下載影像
<a name="api-gateway-content-encodings-example-download-image-from-lambda"></a>

從 Lambda 下載二進位 Blob 格式的影像檔 (`image.jpg`)：

```
GET /v1/lambda?key=image.jpg HTTP/1.1
Host: abcdefghi.execute-api.us-east-1.amazonaws.com
Content-Type: application/json
Accept: application/octet-stream
```

成功回應如下所示：

```
200 OK HTTP/1.1

[raw bytes]
```

從 Lambda 下載 Base64 編碼字串格式的影像檔 (`image.jpg`) 並格式化為 JSON 屬性：

```
GET /v1/lambda?key=image.jpg HTTP/1.1
Host: abcdefghi.execute-api.us-east-1.amazonaws.com
Content-Type: application/json
Accept: application/json
```

成功回應如下所示：

```
200 OK HTTP/1.1

{
  "image": "W3JhdyBieXRlc10="
}
```

## 將影像上傳至 Lambda
<a name="api-gateway-content-encodings-example-upload-image-to-lambda"></a>

將二進位 Blob 格式的影像檔 (`image.jpg`) 上傳至 Lambda：

```
PUT /v1/lambda?key=image.jpg HTTP/1.1
Host: abcdefghi.execute-api.us-east-1.amazonaws.com
Content-Type: application/octet-stream
Accept: application/json

[raw bytes]
```

成功回應如下所示：

```
200 OK            
```

將 Base64 編碼字串格式的影像檔 (`image.jpg`) 上傳至 Lambda：

```
PUT /v1/lambda?key=image.jpg HTTP/1.1
Host: abcdefghi.execute-api.us-east-1.amazonaws.com
Content-Type: application/json
Accept: application/json

W3JhdyBieXRlc10=
```

成功回應如下所示：

```
200 OK           
```