シンプルなAPI Gateway + Lambda + CDKデプロイ構成
ブログ用のシンプルな構成です。API Gateway経由でLambdaを呼び出すだけの最小構成。
📁 プロジェクト構造
my-blog-api/
├── src/
│ └── lambda/
│ └── api_handler/
│ ├── index.py ← あなたのLambdaコード
│ └── requirements.txt ← 依存関係(あれば)
├── lib/
│ └── api-stack.ts ← CDKスタック
├── bin/
│ └── app.ts ← CDKエントリーポイント
├── cdk.json
└── package.json
1️⃣ Lambda関数(src/lambda/api_handler/index.py)
# src/lambda/api_handler/index.py
import json
import boto3
import os
def handler(event, context):
"""
シンプルなAPIハンドラー
"""
print(f"Received event: {json.dumps(event)}")
2️⃣ CDKスタック(lib/api-stack.ts)
// lib/api-stack.ts
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { PythonFunction } from '@aws-cdk/aws-lambda-python-alpha';
import { RestApi, LambdaIntegration } from 'aws-cdk-lib/aws-apigateway';
import { Runtime } from 'aws-cdk-lib/aws-lambda';
export class ApiStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// 1. Lambda関数を作成
const lambdaFn = new PythonFunction(this, 'MyApiLambda', {
entry: 'src/lambda/api_handler', // ディレクトリ指定(動的に)
handler: 'handler', // 関数名
runtime: Runtime.PYTHON_3_12,
functionName: 'my-simple-api',
environment: {
'ENVIRONMENT': 'dev'
}
});
// 2. API Gatewayを作成
const api = new RestApi(this, 'MyApi', {
restApiName: 'Simple API',
description: 'Simple API Gateway with Lambda'
});
// 3. ルート(/)にLambdaを統合
const rootIntegration = new LambdaIntegration(lambdaFn);
api.root.addMethod('ANY', rootIntegration); // すべてのメソッドを許可
// 4. 出力を表示
new cdk.CfnOutput(this, 'ApiUrl', {
value: api.url,
description: 'API Gateway URL'
});
}
}
3️⃣ CDKエントリーポイント(bin/app.ts)
// bin/app.ts
#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { ApiStack } from '../lib/api-stack';
const app = new cdk.App();
new ApiStack(app, 'MySimpleApiStack', {
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION || 'ap-northeast-1'
}
});
4️⃣ 設定ファイル
cdk.json
{
"app": "npx ts-node --prefer-ts-exts bin/app.ts",
"watch": {
"include": ["**"],
"exclude": ["README.md", "cdk*.json", "**/*.d.ts", "**/*.js", "tsconfig.json", "package*.json", "yarn.lock", "node_modules", "test"]
},
"context": {
"@aws-cdk/aws-lambda:recognizeLayerVersion": true
}
}
package.json
{
"name": "my-blog-api",
"version": "1.0.0",
"scripts": {
"build": "tsc",
"watch": "tsc -w",
"cdk": "cdk",
"deploy": "cdk deploy",
"synth": "cdk synth"
},
"devDependencies": {
"@types/node": "^20.0.0",
"aws-cdk": "^2.100.0",
"typescript": "^5.0.0"
},
"dependencies": {
"@aws-cdk/aws-lambda-python-alpha": "^2.100.0-alpha.0",
"aws-cdk-lib": "^2.100.0",
"constructs": "^10.0.0",
"source-map-support": "^0.5.21"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"declaration": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": false,
"inlineSourceMap": true,
"inlineSources": true,
"experimentalDecorators": true,
"strictPropertyInitialization": false,
"typeRoots": ["./node_modules/@types"],
"outDir": "lib",
"rootDir": "."
},
"exclude": ["node_modules", "cdk.out"]
}
🚀 デプロイ手順
# 1. プロジェクト作成
mkdir my-blog-api && cd my-blog-api
# 2. CDK初期化
cdk init app --language=typescript
# 3. 上記のファイルを配置
# 4. 依存関係インストール
npm install
# 5. CDKブートストラップ(初回のみ)
cdk bootstrap
# 6. デプロイ
cdk deploy
# 7. 出力されたURLにアクセス
curl https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/prod/
🧪 テスト
デプロイ後、API GatewayのURLにアクセス:
# GETリクエスト
curl https://your-api-url/prod/
# POSTリクエスト
curl -X POST https://your-api-url/prod/ \
-H "Content-Type: application/json" \
-d '{"name": "test"}'
📝 ブログ用ポイント
- 最小構成: Lambda + API Gateway だけのシンプルさ
- Python Lambda: CDKでPython関数を簡単にデプロイ
- 環境変数: 環境ごとの設定が可能
- CORS対応: フロントエンドからのアクセスも考慮
これでブログ記事が書けます!🎉