CDKを使ってAPI Gateway + Lambda を作成する方法

API Gatewayの作成

API Gatewayの作成には RestApiクラス で作成します。 LambdaをAPI Gatewayと連携する場合、RestApiオブジェクト の addResouce メソッドで許可するパスを追加します。

例 API Gatewayの作成サンプル

    const apiGateway = new RestApi(this, `${PREFIX}TestApiGateway`, {
      restApiName: `${PREFIX}TestApiGateway`,
      deployOptions: {
        stageName: 'v1',
        loggingLevel: MethodLoggingLevel.INFO,
        metricsEnabled: true,
      },
      defaultCorsPreflightOptions: {
        allowOrigins: Cors.ALL_ORIGINS,
        allowMethods: Cors.ALL_METHODS,
        allowHeaders: [...Cors.DEFAULT_HEADERS, 'x-requested-witdh'],
        exposeHeaders: ['content-dispoition'],
        statusCode: 200,
      },
      // cloudWatchRole: true,
    });

    const api = apiGateway.root;
    // LambdaIntegrationは、API Gateway の Lambda プロキシ統合
    api.addResource('hello').addMethod('GET', new LambdaIntegration(lambda));
    return apiGateway;

サンプル

VPCとLambdaも含めたサンプル

参考

例 lib/user-stack.ts

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Cors, LambdaIntegration, MethodLoggingLevel, RestApi } from 'aws-cdk-lib/aws-apigateway';
import { Vpc } from 'aws-cdk-lib/aws-ec2';
import { Runtime } from 'aws-cdk-lib/aws-lambda';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';

const PREFIX = "TestCA-"

export class CognitoLambdaStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const vpc = this.getVpc();
    const lambda = this.getLambda(vpc);
    const apiGateway = this.getApiGateway(vpc, lambda);
  }

  private getVpc(): Vpc {
    const vpc = new Vpc(this, `${PREFIX}TestVpc`, {
      vpcName: `${PREFIX}TestApiVpc`,
      natGateways: 1,
      availabilityZones: ['ap-northeast-1a'],
    });
    return vpc;
  }

  private getLambda(vpc: Vpc) {
    const lambda = new NodejsFunction(this, `${PREFIX}TestLambda`, {
      functionName: `${PREFIX}TestLambda`,
      entry: 'app/src/lambdaHandler.ts',
      depsLockFilePath: 'app/package-lock.json',
      handler: 'lambdaHandler',
      runtime: Runtime.NODEJS_20_X,
      timeout: cdk.Duration.minutes(1),
      vpc,
      vpcSubnets: {
        subnets: vpc.privateSubnets,
      },
    });
    return lambda;
  }

  private getApiGateway(vpc: Vpc, lambda: NodejsFunction) {
    const apiGateway = new RestApi(this, `${PREFIX}TestApiGateway`, {
      restApiName: `${PREFIX}TestApiGateway`,
      deployOptions: {
        stageName: 'v1',
        loggingLevel: MethodLoggingLevel.INFO,
        metricsEnabled: true,
      },
      defaultCorsPreflightOptions: {
        allowOrigins: Cors.ALL_ORIGINS,
        allowMethods: Cors.ALL_METHODS,
        allowHeaders: [...Cors.DEFAULT_HEADERS, 'x-requested-witdh'],
        exposeHeaders: ['content-dispoition'],
        statusCode: 200,
      },
      // cloudWatchRole: true,
    });

    const api = apiGateway.root;
    // LambdaIntegrationは、API Gateway の Lambda プロキシ統合
    api.addResource('hello').addMethod('GET', new LambdaIntegration(lambda));
    return apiGateway;
  }
}