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

如何将AWS API Gateway集成响应转换为HTTP 204 No Content响应?

问题:API Gateway返回204 No Content时触发500错误

我有一个对接SQS的API Gateway POST方法,原本正常返回200 OK和空JSON体。现在想让它返回无负载的204 No Content响应,但尝试在响应模板中设置#set($context.responseOverride.status = 204)时,会返回500内部服务器错误;换成设置202 Accepted则可以正常工作。

原CloudFormation配置片段:

RestPost:
  Type: AWS::ApiGateway::Method
  Properties:
    # 其他配置省略
    Integration:
      # 其他集成配置省略
      IntegrationResponses:
        - StatusCode: 200
          ResponseTemplates:
            application/json: |
              {}  ## a minimal JSON document
    MethodResponses:
      - StatusCode: 200

原因分析

HTTP 204 No Content的规范要求响应必须完全没有内容体,哪怕是空的JSON对象{}也违反了这个规则。API Gateway检测到204响应同时存在内容体时,会抛出500错误。而202 Accepted允许存在内容体,所以设置202时可以正常工作。

解决方案

方式1:直接映射集成响应到204(推荐)

修改集成响应和方法响应的配置,直接将SQS返回的200映射为204,同时确保不生成任何响应体:

RestPost:
  Type: AWS::ApiGateway::Method
  Properties:
    # 其他配置保持不变
    Integration:
      # 其他集成配置保持不变
      IntegrationResponses:
        - StatusCode: 204  # 直接将集成返回的200映射为204
          ResponseTemplates:
            application/json: ""  # 空模板,不生成任何响应体
    MethodResponses:
      - StatusCode: 204
        ResponseModels: {}  # 明确指定无响应模型

方式2:使用responseOverride(兼容原有映射)

如果需要保留原有集成响应的200状态码映射,仅通过模板覆盖状态码,则需要确保模板不输出任何内容:

RestPost:
  Type: AWS::ApiGateway::Method
  Properties:
    # 其他配置保持不变
    Integration:
      # 其他集成配置保持不变
      IntegrationResponses:
        - StatusCode: 200
          ResponseTemplates:
            application/json: |
              #set($context.responseOverride.status = 204)
              # 这里不要输出任何内容,包括空对象或空格
    MethodResponses:
      - StatusCode: 200
      - StatusCode: 204
        ResponseModels: {}

关键注意事项

  • 204响应的内容体必须为空,任何字符(包括空格、换行)都可能导致错误
  • 必须在MethodResponses中显式定义204状态码,且ResponseModels设为空对象,避免API Gateway默认添加响应模型
  • 两种方式都要确保响应模板没有输出任何内容

内容的提问来源于stack exchange,提问作者Nick Breen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:45:12