AWS API Gateway集成Step Function执行成功仍返回500错误
解决方案
核心原因
你遇到的500错误是因为API Gateway收到Step Functions StartExecution 接口的成功响应后,没有匹配到对应的集成响应映射规则,无法将后端返回转换为合法的API响应返回给调用方,所以抛出内部错误。
配置步骤
1. 校验基础配置
- 确认API Gateway执行角色已包含
states:StartExecution权限(你场景中Step Functions可以正常启动,该配置已正确,可跳过校验) - 确认集成配置参数正确:集成类型为
AWS,服务名为States,HTTP方法为POST,动作填StartExecution
2. 配置集成响应映射
这是解决问题的核心步骤:
- 进入API Gateway对应集成的「集成响应」配置页
- 新增响应规则:
- 响应状态码正则填写
2\d{2},匹配Step Functions返回的所有2xx成功状态码 - 关联方法响应状态码为
202 Accepted(异步场景推荐用202状态码,也可根据业务需求选200) - 新增
application/json类型的映射模板,模板内容填写$input.json('$'),即可透传Step Functions返回的执行ARN、启动时间等信息
- 响应状态码正则填写
- 进入「方法响应」配置页,确认已存在你上面选的状态码(如202)的配置项
3. 部署验证
修改配置后必须将API部署到对应的调用阶段,配置才会生效。调用成功后你会收到如下格式的正常响应:
{ "executionArn": "arn:aws:states:us-east-1:123456789012:execution:你的状态机名称:执行ID", "startDate": 1620000000.0 }
Terraform 配置参考
如果你用REST API,核心配置示例如下:
resource "aws_api_gateway_integration" "sfn_start" { rest_api_id = aws_api_gateway_rest_api.example.id resource_id = aws_api_gateway_resource.example.id http_method = aws_api_gateway_method.example.http_method type = "AWS" uri = "arn:aws:apigateway:${var.region}:states:action/StartExecution" credentials = aws_iam_role.api_gateway_sfn_role.arn request_templates = { "application/json" = <<EOF { "input": "$util.escapeJavaScript($input.body)", "stateMachineArn": "${var.sfn_arn}" } EOF } } # 配置2xx集成响应映射 resource "aws_api_gateway_integration_response" "sfn_2xx" { rest_api_id = aws_api_gateway_rest_api.example.id resource_id = aws_api_gateway_resource.example.id http_method = aws_api_gateway_method.example.http_method status_code = aws_api_gateway_method_response.sfn_202.status_code selection_pattern = "2\\d{2}" response_templates = { "application/json" = "$input.json('$')" } } # 配置方法响应202 resource "aws_api_gateway_method_response" "sfn_202" { rest_api_id = aws_api_gateway_rest_api.example.id resource_id = aws_api_gateway_resource.example.id http_method = aws_api_gateway_method.example.http_method status_code = "202" }
内容的提问来源于stack exchange,提问作者firestreak
相关产品推荐
相关产品推荐

