

# 在 API Gateway 中为 API 启用负载压缩
<a name="api-gateway-enable-compression"></a>

您可以使用 API Gateway 控制台、AWS CLI 或AWS开发工具包为 API 启用压缩。

对于现有 API，您必须在启用压缩后部署 API，这样更改才能生效。对于新 API，您可以在 API 设置完成后部署该 API。

**注意**  
最高优先级内容编码必须是 API Gateway 支持的编码。如果不是，将不对响应负载应用压缩。

**Topics**
+ [使用 API Gateway 控制台为 API 启用负载压缩](#api-gateway-enable-compression-console)
+ [使用 AWS CLI 为 API 启用负载压缩](#api-gateway-enable-compression-cli)
+ [API Gateway 支持的内容编码](#api-gateway-supported-content-encodings)

## 使用 API Gateway 控制台为 API 启用负载压缩
<a name="api-gateway-enable-compression-console"></a>

以下过程介绍如何为 API 启用负载压缩。

**使用 API Gateway 控制台启用负载压缩**

1. 通过以下网址登录到 Amazon API Gateway 控制台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 选择现有 API 或者创建新 API。

1. 在主导航窗格中，选择 **API 设置**。

1. 在 **API 详细信息**部分中，选择**编辑**。

1. 开启**内容编码**以启用负载压缩。对于**最小正文大小**，为最小压缩大小输入数字（字节数）。要关闭压缩，请关闭**内容编码**选项。

1. 选择**保存更改**。

## 使用 AWS CLI 为 API 启用负载压缩
<a name="api-gateway-enable-compression-cli"></a>



以下 [create-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-rest-api.html) 命令创建具有有效载荷压缩的 API：

```
aws apigateway create-rest-api \
    --name "My test API" \
    --minimum-compression-size 0
```

以下 [update-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-rest-api.html) 命令为现有 API 启用有效载荷压缩：

```
aws apigateway update-rest-api \
    --rest-api-id 1234567890 \
    --patch-operations op=replace,path=/minimumCompressionSize,value=0
```

`minimumCompressionSize` 属性具有 0 到 10485760（10M 字节）之间的非负整数值。它可测量压缩阈值。如果负载大小小于该值，则不会对负载应用压缩或解压缩。将它设置为零允许对任何负载大小进行压缩。

以下 [update-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-rest-api.html) 命令关闭有效载荷压缩：

```
aws apigateway update-rest-api \
    --rest-api-id 1234567890 \
    --patch-operations op=replace,path=/minimumCompressionSize,value=
```

您也可以将 `value` 设置为空字符串 `""` 或在上一调用中忽略 `value` 属性。

## API Gateway 支持的内容编码
<a name="api-gateway-supported-content-encodings"></a>

API Gateway 支持以下内容编码：
+ `deflate`
+ `gzip`
+ `identity`

根据 [RFC 7231](https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.4) 规范，API Gateway 还支持以下 `Accept-Encoding` 标头格式：
+ `Accept-Encoding:deflate,gzip`
+ `Accept-Encoding:`
+ `Accept-Encoding:*`
+ `Accept-Encoding:deflate;q=0.5,gzip;q=1.0`
+ `Accept-Encoding:gzip;q=1.0,identity;q=0.5,*;q=0`