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

通过CloudFormation部署REST API出现503错误:如何配置使Lambda返回json.dumps()生成的数据

解决API Gateway 503错误并让Lambda返回JSON数据

首先,你遇到的503错误大概率是因为API Gateway没有部署到Stage——手动部署时你肯定完成了"部署API"的步骤,但CloudFormation模板里缺少了关键的AWS::ApiGateway::Deployment资源,这是API能够对外访问的必要环节。

另外,针对你提到的Method Response问题:当使用AWS_PROXY集成类型时,API Gateway会完全透传Lambda的响应结果,不需要手动配置Method Response或Integration Response的响应体类型。不过我们还是一步步来修正你的配置:

1. 添加API Gateway Deployment资源

必须添加这个资源来将你的API部署到一个Stage,否则创建的API只是"草稿"状态,无法被访问。示例配置如下:

APIGatewayDeployment:
  Type: AWS::ApiGateway::Deployment
  Properties:
    RestApiId: !Ref APIGatewayRestAPI
    StageName: prod # 这里可以改成你想要的Stage名称,比如dev/test
  DependsOn: APIGateWayMethod # 必须依赖Method资源,确保部署时Method已经创建完成

2. 确保Lambda有API Gateway的调用权限

你需要添加一个AWS::Lambda::Permission资源,允许API Gateway服务调用你的Lambda函数,否则即使部署了API,也可能出现权限相关的错误:

LambdaInvokePermission:
  Type: AWS::Lambda::Permission
  Properties:
    Action: lambda:InvokeFunction
    FunctionName: !GetAtt MyLambda.Arn
    Principal: apigateway.amazonaws.com
    SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${APIGatewayRestAPI}/${APIGatewayDeployment.StageName}/GET/${APIGatewayResource}"

3. Lambda函数返回正确的响应格式

在你的Lambda代码中,需要返回符合AWS_PROXY要求的结构,这样API Gateway才能正确解析并返回JSON给调用者:

import json

def lambda_handler(event, context):
    # 你的业务逻辑示例
    data = {"message": "Hello from Lambda", "data": {"key": "value"}}
    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json" # 指定响应的Content-Type为JSON
        },
        "body": json.dumps(data) # 将Python字典转为JSON字符串
    }

可选:显式配置Method Response(和手动部署对齐)

虽然AWS_PROXY模式下不需要额外配置,但如果你想和手动部署的配置完全一致,可以在Method资源中添加MethodResponses配置:

APIGateWayMethod:
  Type: AWS::ApiGateway::Method
  Properties:
    HttpMethod: GET
    ResourceId: !Ref APIGatewayResource
    RestApiId: !Ref APIGatewayRestAPI
    Integration:
      IntegrationHttpMethod: POST
      Type: AWS_PROXY
      Uri: !Sub
        - arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations
        - lambdaArn: !GetAtt MyLambda.Arn
    # 新增的Method Response配置,和手动部署对齐
    MethodResponses:
      - StatusCode: 200
        ResponseModels:
          application/json: Empty # 这里用Empty模型即可,AWS_PROXY会透传Lambda响应

总结

核心问题是缺少API Gateway Deployment资源导致503,加上Deployment和Lambda权限配置后,再确保Lambda返回正确的响应结构,就能让JSON数据正常返回给调用者了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 03:27:43