在Serverless Framework中实现多函数共享AWS新HTTP API的方法
关联已有的HTTP API到Serverless Framework函数
我明白你现在的困惑——HTTP API和REST API在Serverless Framework里的配置逻辑确实不一样,不用再找类似restApiRootResourceId的配置了,因为HTTP API的架构设计更简洁,不需要这个参数。下面是具体的解决方案:
1. 在Provider段配置已有HTTP API的ID
和REST API用apiGateway段不同,HTTP API需要用httpApi段来指定已有的API ID。直接替换原来的apiGateway配置即可:
provider: name: aws httpApi: id: xxxxxxx # 替换成你的HTTP API实际ID functions: myFunction: ${file(./lambdas/myFunction.yml)}
2. 在函数事件中配置HTTP API触发
接下来在你的函数配置文件(比如myFunction.yml)里,要使用httpApi类型的事件,而不是原来的http(REST API的事件类型)。示例如下:
handler: handler.main events: - httpApi: path: /your-endpoint-path method: get # 或者post、put等你需要的请求方法
关键说明
HTTP API不需要restApiRootResourceId是因为它的路由系统是直接绑定到整个API实例的,不需要像REST API那样依赖资源层级结构。只要你在provider里指定了正确的HTTP API ID,Serverless Framework就会自动把函数的触发路由关联到这个已有的API上。
如果后续你需要配置更多HTTP API的高级特性(比如自定义域名、CORS、授权器等),都可以在httpApi段里添加对应的配置项,比如:
provider: name: aws httpApi: id: xxxxxxx cors: true domain: name: api.yourdomain.com certificateArn: arn:aws:acm:us-east-1:123456789012:certificate/abc123-xyz456
内容的提问来源于stack exchange,提问作者evdh
相关产品推荐
相关产品推荐

