0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[備忘録]CDKとSAMでローカルにAPI構築

Last updated at Posted at 2025-02-20

まえおき

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,
        });
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?