B-Teck!

お仕事からゲームまで幅広く

【Lambda】SAMのテンプレートに複数のHTTPメソッドを書く

前置き

1つのLambdaでGET、PUT、POST、DELETEを扱いたい要件があったけど何もわからなかったので。

実装

この辺りを参考に、Events配下に対応するMethodのEventを追加してやればよかった。
AWS SAMテンプレートでREST APIの複数メソッドをひとつのLambdaに統合するには? - 銀の弾丸
AWS::Serverless::Function - AWS Serverless Application Model
EventSource - AWS Serverless Application Model

Resources:
  SampleFunction:
    Type: AWS::Serverless::Function
    Properties:
      Events:
        Get:
          Type: Api
          Properties:
            Path: /sample
            Method: GET
        Put:
          Type: Api
          Properties:
            Path: /sample
            Method: PUT
        Post:
          Type: Api
          Properties:
            Path: /sample
            Method: POST
        Delete:
          Type: Api
          Properties:
            Path: /sample
            Method: DELETE

多分Goだとこんな感じで分岐できる。

func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    resp := events.APIGatewayProxyResponse{Body: "Hello", StatusCode: http.StatusOK}

    // 任意のHTTPメソッドの分岐
    switch request.HTTPMethod {
    case http.MethodGet:
        return resp, nil
    case http.MethodPost:
        return resp, nil
    case http.MethodDelete:
        return resp, nil
    case http.MethodPut:
        return resp, nil
    default:
        return nil, errors.New("想定外のHTTPメソッドがリクエストされました")
    }
}