まえおき
CDKで記述したLambdaとAPI Gatewayをローカルで動かしたときの手順をここに残します。
前提
以下のコマンドによって作成されたCDKのテンプレートを使用して、CDKを実装している。
cdk init app --language typescript
テンプレート出力
以下のコマンドを実行して、テンプレート出力をする。
※template.yamlが既に存在する場合は削除してから実行
cdk synth > template.yaml
以下のコマンドを実行して、出力されたテンプレートをcdk.out
ディレクトリに移動させる。
mv template.yaml cdk.out/template.yaml
API起動
以下のコマンドを実行して、テンプレートを元にAPIを起動する。
sam local start-api -t cdk.out/template.yaml
Tips
API Gatewayのアクセス可能なURLを出力
CDK内で、cdk.CfnOutput()
を記述をすることでコンソール上にアクセス可能なAPIのURLが出力される。
import { NestedStack } from "aws-cdk-lib";
import type { Construct } from "constructs";
import * as cdk from "aws-cdk-lib";
import * as apigateway from "aws-cdk-lib/aws-apigateway";
export class ApiStack extends NestedStack {
constructor(scope: Construct, id: string) {
super(scope, id);
// LambdaやAPI Gatewayの作成
...
const api = new apigateway.RestApi(this, "Api", {
// 設定など
...
});
new cdk.CfnOutput(this, "ApiEndpoint", {
value: api.url,
});
}
}