如何将动态数据从HTTP触发的Step Functions返回至HTTP响应
实现HTTP触发的Step Functions返回Lambda动态数据
要解决这个问题,核心是把默认的异步启动状态机改成同步调用模式,让API Gateway等待状态机执行完成后,直接获取Lambda的输出并返回给HTTP请求。以下是具体实现步骤:
1. 修改Step Functions触发的调用模式
默认HTTP触发Step Functions是异步执行(仅返回executionArn和startDate),需要改为同步调用(对应StartSyncExecution接口),这样API Gateway会等待状态机执行完毕,拿到完整的执行结果。
在serverless.yml的Step Functions HTTP事件配置中,通过request.parameters指定调用类型:
stepFunctions: stateMachines: MyStateMachine: definition: StartAt: RunLambdaTask States: RunLambdaTask: Type: Task Resource: !GetAtt MyLambda.Arn End: true # 让该任务的输出作为状态机最终输出 events: - http: path: /my-service method: post integration: aws request: parameters: IntegrationType: AWS IntegrationSubtype: StepFunctions-StartExecution InvocationType: RequestResponse # 同步调用标识 PayloadFormatVersion: "1.0" Credentials: "${self:provider.roleArn}" # 确保API Gateway有调用权限 template: application/json: | { "input": "$util.escapeJavaScript($input.json('$'))", "stateMachineArn": "${self:resources.Outputs.MyStateMachine.Value}" }
2. 配置API Gateway响应模板提取Lambda数据
同步调用完成后,API Gateway会收到包含状态机执行结果的响应:其中$.output字段就是Lambda返回的动态数据,$.status字段标识执行状态(SUCCEEDED/FAILED等)。
在HTTP事件的response部分配置模板,根据执行状态返回对应内容和HTTP状态码:
response: template: application/json: | #if($input.path('$.status') == 'SUCCEEDED') $input.path('$.output') # 直接返回Lambda的输出 #else { "error_code": "$input.path('$.error')", "error_message": "$input.path('$.cause')" } #end statusCodes: 200: pattern: "^SUCCEEDED$" # 执行成功返回200 500: pattern: "^FAILED$" # 执行失败返回500
3. 配置必要的权限
确保API Gateway的角色拥有同步调用Step Functions的权限,在provider.iamRoleStatements中添加:
provider: name: aws runtime: nodejs18.x iamRoleStatements: - Effect: Allow Action: - states:StartSyncExecution Resource: !Ref MyStateMachine
关键说明
- 同步调用的状态机执行最长超时为5分钟,如果你的业务流程超过这个时间,这种方式不适用,需要改用异步执行+回调的模式
- 状态机的最终输出由最后一个Task的返回值决定,确保Lambda函数返回你需要的结构化数据(比如包含自定义状态码、错误信息的JSON)
内容的提问来源于stack exchange,提问作者Ben Swinburne
相关产品推荐
相关产品推荐

