You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS SAM中AWS::Serverless::Api的MinimumCompressionSize对Lambda响应无效?

问题分析与解决

核心原因

你遇到的问题并非template.yaml配置错误,而是SAM Local(sam local start-api)工具本身不支持模拟AWS API Gateway的响应压缩特性。MinimumCompressionSize是AWS云端API Gateway的原生功能,但本地开发工具尚未实现该功能的模拟,所以即使配置正确,本地测试时也不会触发压缩。

配置正确性验证

你的template.yaml配置完全符合AWS SAM文档要求:

  • 已为AWS::Serverless::Api资源正确设置MinimumCompressionSize: 0
  • Lambda函数已正确关联到目标Api资源

完整配置代码:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-app

  Sample SAM Template for sam-app
Globals:
  Function:
    Timeout: 3
    MemorySize: 128
Resources:
  CompressedApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: "Prod"
      MinimumCompressionSize: 0
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs16.x
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api 
          Properties:
            Path: /hello
            Method: get
            RestApiId: !Ref CompressedApi

对应的Lambda代码也无问题:

exports.lambdaHandler = async (event, context) => {
    try {
        response = {
            'statusCode': 200,
            'body': JSON.stringify({
                message: 'hello world'
            })
        }
    } catch (err) {
        console.log(err);
        return err;
    }

    return response
};

云端验证方法

若要确认压缩功能是否正常工作,需将应用部署到AWS云端后测试:

  1. 执行部署命令:
    sam deploy --guided
    
  2. 部署完成后,使用curl或浏览器访问生成的API Gateway端点,检查响应头是否包含Content-Encoding: gzip(需确保请求头带有Accept-Encoding: gzip, deflate)。

本地测试替代方案

如果需要在本地测试压缩效果,可选择以下两种方式:

  • Lambda函数内手动压缩:使用Node.js的zlib库对响应body进行gzip压缩,同时在响应头中添加Content-Encoding: gzip和Content-Type: application/json
  • 本地反向代理:启动Nginx或其他代理服务,配置压缩规则,将请求转发到sam local的端口,通过代理实现压缩。

内容的提问来源于stack exchange,提问作者Milan Donhowe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 19:25:16