CloudFormationを使ってHTTP API(API Gateway)を構築してみる

API GatewayでHTTP APIを構築するサンプルが欲しかったので、CloudFormationで環境を構築しました。 その際に作成したCloudFormationテンプレートを紹介します。
2022.05.06

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

API GatewayでHTTP APIを構築するサンプルが欲しかったので、CloudFormationで環境を構築しました。

その際に作成したCloudFormationテンプレートを紹介します。

構成図

構成は次のような感じのシンプルなHTTP APIです。

CloudFormationスタックの作成

次のCloudFormationスタックのクイック作成リンクを開いて、CloudFormationスタックを作成します。

または、次のyamlを template.yml として作成してCloudFormationのテンプレートとしてアップロードして作成します。

template.yml

---
AWSTemplateFormatVersion: '2010-09-09'
Description: 'HTTP API Sample'

Resources:
  LambdaServiceRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
        Version: '2012-10-17'
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
  Lambda:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: |-
          exports.handler = async (event, context) => {
            console.log("EVENT: \n" + JSON.stringify(event, null, 2));
            return '{"message": "Hello, World!!"}';
          }
      Role: !GetAtt LambdaServiceRole.Arn
      Handler: index.handler
      Runtime: nodejs14.x
    DependsOn:
      - LambdaServiceRole
  HttpApi:
    Type: AWS::ApiGatewayV2::Api
    Properties:
      Name: HttpApiSample
      ProtocolType: HTTP
  HttpApiDefaultStage:
    Type: AWS::ApiGatewayV2::Stage
    Properties:
      ApiId: !Ref HttpApi
      StageName: "$default"
      AutoDeploy: true
  HttpApiHelloIntegration:
    Type: AWS::ApiGatewayV2::Integration
    Properties:
      ApiId: !Ref HttpApi
      IntegrationType: AWS_PROXY
      IntegrationUri: !GetAtt Lambda.Arn
      PayloadFormatVersion: '2.0'
  HttpApiHelloIntegrationPermission:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:InvokeFunction
      FunctionName: !GetAtt Lambda.Arn
      Principal: apigateway.amazonaws.com
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*/hello"
  HttpApiHelloRoute:
    Type: AWS::ApiGatewayV2::Route
    Properties:
      ApiId: !Ref HttpApi
      RouteKey: GET /hello
      AuthorizationType: NONE
      Target: !Sub "integrations/${HttpApiHelloIntegration}"

動作確認する

スタックの作成が完了すると、API GatewayにHTTP APIが作成されています。

マネジメントコンソールを確認すると、呼び出すためのURLが生成されているので、それに /hello を追加してアクセスするとHello, World!!を返すAPIができていることがわかります。

終わりに

HTTP APIを1クリックでサクッと作って試すためのサンプルが欲しくて探してみたのですが、シンプルなものが見つからず自分で作りました。

とりあえず動くものを使いたい方にはこのCloudFormationテンプレートが使えると思います。