如何用Serverless Framework+OpenAPI实现API Gateway传JSON至Step Functions
问题解决指引
API Gateway返回500错误大多和请求格式不匹配、集成配置漏项、权限细节没到位有关,结合你的配置,重点查以下几点:
1. 补全OpenAPI集成的请求模板
你现在的OpenAPI配置里没加requestTemplates,API Gateway没法把收到的JSON payload转换成Step Functions StartExecution要求的格式。StartExecution要求的请求体必须是这个结构:
{ "stateMachineArn": "你的状态机ARN", "input": "JSON字符串格式的输入参数" }
得在x-amazon-apigateway-integration里加请求模板,把API收到的payload转成这个格式:
修改schema.yml:
paths: /api: post: x-amazon-apigateway-integration: credentials: Fn::GetAtt: [ testRole, Arn ] uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:states:action/StartExecution httpMethod: POST type: aws # 新增请求模板,转换payload格式 requestTemplates: application/json: | { "stateMachineArn": "${cf:webhook-json-dev-hellostepfunc1}", "input": "$util.escapeJavaScript($input.json('$'))" } responses: default: statusCode: 200 # 可选:添加响应模板,格式化返回结果 responseTemplates: application/json: | #set($inputRoot = $input.path('$')) { "executionArn": "$inputRoot.executionArn", "startDate": $inputRoot.startDate }
这里${cf:webhook-json-dev-hellostepfunc1}是Serverless自动生成的状态机ARN引用(格式是cf:服务名-阶段名-状态机名),嫌麻烦也可以直接写状态机的完整ARN。
2. 修正Serverless配置里的OpenAPI文件路径
你的serverless.yml里openApiIntegration.inputFile写的是serverless.doc.yml,但实际你的OpenAPI schema是./schema.yml,路径不对会导致集成配置没生效,改成:
openApiIntegration: autoMock: true package: true inputFile: schema.yml # 改成实际的schema文件路径 outputFile: api.yml
3. 核对执行角色的权限细节
虽然你配了states:StartExecution权限,但还是得确认:
- 信任策略有没有写错:确保
Principal是apigateway.amazonaws.com,你的配置里是对的,但再检查一遍拼写没毛病。 - 资源范围要不要收窄:如果不想用
*,可以指定具体的状态机ARN,比如:
Statement: - Effect: Allow Action: states:StartExecution Resource: !Ref hellostepfunc1 # 直接引用Serverless生成的状态机资源
4. 查CloudWatch日志找具体错误
500错误的根因得看CloudWatch日志:
- 进AWS控制台的CloudWatch服务
- 找到对应API Gateway的日志组(一般是
API-Gateway-Execution-Logs_{API ID}/dev这个格式) - 看最近的请求日志,里面会写具体错在哪(比如请求格式不对、权限不够、状态机ARN不存在之类的)
5. 重新部署服务
改完配置后,跑命令重新部署:
serverless deploy
测试验证
部署完在Postman发POST请求,带个JSON payload试试:
{ "key": "value" }
配置对的话,会返回Step Functions的执行信息,状态码200。
内容的提问来源于stack exchange,提问作者Fred
相关产品推荐
相关产品推荐

