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

如何在AWS SAM应用中为Customers REST API同时声明GET和POST HTTP方法?

如何为AWS SAM中的Customers API添加GET和POST两种方法?

没问题!要给你的/customers REST API端点同时支持GET和POST方法,只需要在函数的Events配置下新增一个对应POST方法的事件条目即可。下面是修改后的完整AWS SAM模板:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: ""
Globals:
  Function:
    Timeout: 59
Resources:
  HealthFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: index.handler
      Runtime: nodejs14.x
      Architectures:
        - x86_64
    Events:
      Health:
        Type: Api
        Properties:
          Path: /health
          Method: get
      CustomersGet:
        Type: Api
        Properties:
          Path: /customers
          Method: get
      CustomersPost:
        Type: Api
        Properties:
          Path: /customers
          Method: post
Outputs:
  HealthApi:
    Description: "API Gateway endpoint URL for Prod for Health function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/health"
  CustomersGetApi:
    Description: "API Gateway endpoint URL for Prod for Customers GET function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/customers"
  CustomersPostApi:
    Description: "API Gateway endpoint URL for Prod for Customers POST function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/customers"

关键修改说明:

  • 我把原来的Customers事件重命名为CustomersGet(只是为了配置更清晰,你也可以保留原名),然后新增了CustomersPost事件,两者路径都是/customers,但方法分别指定为get和post
  • 顺便修正了Outputs里的一处小错误:原来的CustomersApi描述误写为“Health function”,现在改成了对应方法的准确描述,并且新增了POST方法的输出条目(如果不需要单独输出POST的URL,也可以只保留一个输出项,不过分开展示会更清晰)

修改完成后,你的/customers端点就会同时响应GET和POST请求,两个请求都会触发同一个HealthFunction函数。如果之后你想让不同方法触发不同的处理函数,只需要把对应的事件配置放到另一个Function资源下即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 10:27:34