DEV Community

Cover image for 2026年 AWS Lambda API サーバーレス活用術
Akira
Akira

Posted on • Originally published at apidog.com

2026年 AWS Lambda API サーバーレス活用術

要約

AWS Lambda APIは、開発者がサーバーレス関数をプログラムでデプロイ、管理、呼び出すためのRESTfulエンドポイントを提供します。IAM認証、関数管理、同期・非同期呼び出し、イベントソースマッピング、同時実行制限など、本番環境を意識したサーバーレス運用を効率化するAPI群です。本記事は認証設定から関数デプロイ、呼び出し、イベント連携、レイヤー管理、本番戦略まで、実装中心で説明します。

Apidogを今すぐ試す

はじめに

AWS Lambdaは、100万人以上のアクティブユーザーのために毎月数兆のリクエストを処理しています。サーバーレス開発や自動化、イベント駆動設計にはLambda APIの自動統合が必須です。IaCやCI/CDパイプラインにLambda APIの自動化を組み込むことで、手作業のミスや工数を削減し、ブルー/グリーンリリースや動的スケーリングも可能になります。

この記事では、Lambda APIの認証、関数管理、呼び出しパターン、イベント連携、レイヤー、そして本番運用のための導入手順を実例コードとともに紹介します。

AWS Lambda APIとは?

AWS Lambdaはサーバーレス関数の作成、デプロイ、呼び出し、監視などをRESTful API経由で管理できます。主なAPI操作は以下です。

  • 関数の作成/更新/削除
  • コードのデプロイ・バージョン管理
  • 同期・非同期呼び出し
  • イベントソース連携(SQS, Kinesis, DynamoDB, S3等)
  • レイヤー・依存関係管理
  • バージョン/エイリアス/トラフィックシフト
  • 同時実行/予約容量制御
  • ログ/監視連携

主要機能

機能 説明
RESTful API 標準HTTPSエンドポイント
IAM認証 AWS署名バージョン4
非同期呼び出し イベント駆動処理
同期呼び出し リクエスト-レスポンス
イベントソース 200+ AWSサービス統合
レイヤー 共有コード・依存関係
バージョン/エイリアス トラフィックシフト・ロールバック
プロビジョニング同時実行 コールドスタート回避

Lambdaランタイムサポート

ランタイム バージョン ユースケース
Node.js 18.x, 20.x APIバックエンド・イベント処理
Python 3.9, 3.10, 3.11 データ処理・ML
Java 11, 17, 21 エンタープライズ
Go 1.x 高性能API
Rust 1.x 低レイテンシ
.NET 6, 8 Windowsワークロード
Ruby 3.x ウェブアプリ
カスタム 任意 コンテナランタイム

APIアーキテクチャの概要

Lambda APIエンドポイント例:

https://lambda.{region}.amazonaws.com/2015-03-31/
Enter fullscreen mode Exit fullscreen mode

APIバージョン

バージョン ステータス ユースケース
2015-03-31 現行 全操作
2018-01-31 ランタイムAPI カスタムランタイム

はじめに:認証設定

ステップ1:AWSアカウントとIAMユーザーの作成

  1. AWSコンソールへアクセス
  2. アカウント作成
  3. IAMユーザー作成し、Lambda実行ポリシーをアタッチ

ステップ2:IAM認証情報の生成

# AWS CLIでアクセスキー作成
aws iam create-access-key --user-name lambda-deployer
Enter fullscreen mode Exit fullscreen mode

出力されたAccessKeyId, SecretAccessKeyを安全に保管します。

# ~/.aws/credentials
[lambda-deployer]
aws_access_key_id = AKIAIOSFODNN7EXAMPLE
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

# または環境変数
export AWS_ACCESS_KEY_ID="AKIAIOSFODNN7EXAMPLE"
export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
export AWS_DEFAULT_REGION="us-east-1"
Enter fullscreen mode Exit fullscreen mode

ステップ3:AWS署名バージョン4を理解する

Lambda APIリクエストは全てSigV4署名が必要です。Node.jsの場合の署名クラス例:

const crypto = require('crypto');

class AWSSigner {
  constructor(accessKeyId, secretAccessKey, region, service = 'lambda') {
    this.accessKeyId = accessKeyId;
    this.secretAccessKey = secretAccessKey;
    this.region = region;
    this.service = service;
  }

  sign(request, body = null) {
    const now = new Date();
    const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, '');
    const dateStamp = amzDate.slice(0, 8);

    // Canonicalリクエスト作成
    const hashedPayload = body ? crypto.createHash('sha256').update(body).digest('hex') : 'UNSIGNED-PAYLOAD';
    const canonicalUri = request.path;
    const canonicalQuerystring = request.query || '';
    const canonicalHeaders = `host:${request.host}\nx-amz-date:${amzDate}\n`;
    const signedHeaders = 'host;x-amz-date';
    const canonicalRequest = `${request.method}\n${canonicalUri}\n${canonicalQuerystring}\n${canonicalHeaders}\n${signedHeaders}\n${hashedPayload}`;

    // 署名文字列作成
    const algorithm = 'AWS4-HMAC-SHA256';
    const credentialScope = `${dateStamp}/${this.region}/${this.service}/aws4_request`;
    const hash = crypto.createHash('sha256').update(canonicalRequest).digest('hex');
    const stringToSign = `${algorithm}\n${amzDate}\n${credentialScope}\n${hash}`;

    // 署名計算
    const kDate = this.hmac(`AWS4${this.secretAccessKey}`, dateStamp);
    const kRegion = this.hmac(kDate, this.region);
    const kService = this.hmac(kRegion, this.service);
    const kSigning = this.hmac(kService, 'aws4_request');
    const signature = this.hmac(kSigning, stringToSign, 'hex');

    // 認証ヘッダー
    const authorizationHeader = `${algorithm} Credential=${this.accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;

    return {
      'Authorization': authorizationHeader,
      'X-Amz-Date': amzDate,
      'X-Amz-Content-Sha256': hashedPayload
    };
  }

  hmac(key, string, encoding = 'buffer') {
    return crypto.createHmac('sha256', key).update(string).digest(encoding);
  }
}

// 使用例
const signer = new AWSSigner(
  process.env.AWS_ACCESS_KEY_ID,
  process.env.AWS_SECRET_ACCESS_KEY,
  'us-east-1'
);
Enter fullscreen mode Exit fullscreen mode

ステップ4:Lambda APIクライアントの作成

const LAMBDA_BASE_URL = 'https://lambda.us-east-1.amazonaws.com/2015-03-31';

const lambdaRequest = async (path, options = {}) => {
  const url = new URL(`${LAMBDA_BASE_URL}${path}`);
  const method = options.method || 'GET';
  const body = options.body ? JSON.stringify(options.body) : null;

  const signer = new AWSSigner(
    process.env.AWS_ACCESS_KEY_ID,
    process.env.AWS_SECRET_ACCESS_KEY,
    'us-east-1'
  );

  const headers = signer.sign({ method, host: 'lambda.us-east-1.amazonaws.com', path }, body);

  const response = await fetch(url.toString(), {
    method,
    headers: {
      'Content-Type': 'application/json',
      ...headers,
      ...options.headers
    },
    body
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`Lambda API Error: ${error.Message}`);
  }

  return response.json();
};

// 使用例
const functions = await lambdaRequest('/functions');
console.log(`Found ${functions.Functions.length} functions`);
Enter fullscreen mode Exit fullscreen mode

代替手段:AWS SDKを使用する

実運用ではAWS SDKが自動署名+API操作を提供。

const { LambdaClient, ListFunctionsCommand, CreateFunctionCommand, InvokeCommand } = require('@aws-sdk/client-lambda');

const lambda = new LambdaClient({ region: 'us-east-1' });

// 関数リスト
const listCommand = new ListFunctionsCommand({});
const result = await lambda.send(listCommand);

// 関数作成
const createCommand = new CreateFunctionCommand({
  FunctionName: 'my-function',
  Runtime: 'nodejs20.x',
  Role: 'arn:aws:iam::123456789012:role/lambda-execution-role',
  Handler: 'index.handler',
  Code: {
    S3Bucket: 'my-bucket',
    S3Key: 'function.zip'
  }
});

const fn = await lambda.send(createCommand);
Enter fullscreen mode Exit fullscreen mode

関数管理

関数の作成

Lambda関数をAPIで作成:

const createFunction = async (functionConfig) => {
  const response = await lambdaRequest('/functions', {
    method: 'POST',
    body: {
      FunctionName: functionConfig.name,
      Runtime: functionConfig.runtime || 'nodejs20.x',
      Role: functionConfig.roleArn,
      Handler: functionConfig.handler || 'index.handler',
      Code: {
        S3Bucket: functionConfig.s3Bucket,
        S3Key: functionConfig.s3Key
      },
      Description: functionConfig.description || '',
      Timeout: functionConfig.timeout || 3,
      MemorySize: functionConfig.memorySize || 128,
      Environment: {
        Variables: functionConfig.environment || {}
      },
      Tags: functionConfig.tags || {}
    }
  });
  return response;
};

// 使用例
const fn = await createFunction({
  name: 'order-processor',
  roleArn: 'arn:aws:iam::123456789012:role/lambda-execution-role',
  handler: 'index.handler',
  runtime: 'nodejs20.x',
  s3Bucket: 'my-deployments-bucket',
  s3Key: 'order-processor/v1.0.0.zip',
  description: 'Process orders from SQS queue',
  timeout: 30,
  memorySize: 512,
  environment: {
    DB_HOST: 'db.example.com',
    LOG_LEVEL: 'info'
  }
});
console.log(`Function created: ${fn.FunctionArn}`);
Enter fullscreen mode Exit fullscreen mode

コードの直接アップロード

50MB未満のZIPならBase64アップロード可:

const fs = require('fs');
const path = require('path');

const createFunctionWithZip = async (functionName, zipPath) => {
  const zipBuffer = fs.readFileSync(zipPath);
  const base64Code = zipBuffer.toString('base64');

  const response = await lambdaRequest('/functions', {
    method: 'POST',
    body: {
      FunctionName: functionName,
      Runtime: 'nodejs20.x',
      Role: 'arn:aws:iam::123456789012:role/lambda-execution-role',
      Handler: 'index.handler',
      Code: {
        ZipFile: base64Code
      }
    }
  });

  return response;
};

// zip -r function.zip index.js node_modules/
await createFunctionWithZip('my-function', './function.zip');
Enter fullscreen mode Exit fullscreen mode

関数コードの更新

const updateFunctionCode = async (functionName, updateConfig) => {
  const response = await lambdaRequest(`/functions/${functionName}/code`, {
    method: 'PUT',
    body: {
      S3Bucket: updateConfig.s3Bucket,
      S3Key: updateConfig.s3Key,
      Publish: updateConfig.publish || false
    }
  });
  return response;
};

// 使用例
const updated = await updateFunctionCode('order-processor', {
  s3Bucket: 'my-deployments-bucket',
  s3Key: 'order-processor/v1.1.0.zip',
  publish: true
});
console.log(`Updated to version: ${updated.Version}`);
Enter fullscreen mode Exit fullscreen mode

関数設定の更新

const updateFunctionConfig = async (functionName, config) => {
  const response = await lambdaRequest(`/functions/${functionName}/configuration`, {
    method: 'PUT',
    body: {
      Runtime: config.runtime,
      Handler: config.handler,
      Description: config.description,
      Timeout: config.timeout,
      MemorySize: config.memorySize,
      Environment: {
        Variables: config.environment
      }
    }
  });
  return response;
};

// 使用例
const updated = await updateFunctionConfig('order-processor', {
  timeout: 60,
  memorySize: 1024,
  environment: {
    DB_HOST: 'new-db.example.com',
    LOG_LEVEL: 'debug'
  }
});
Enter fullscreen mode Exit fullscreen mode

関数の削除

const deleteFunction = async (functionName, qualifier = null) => {
  const path = qualifier
    ? `/functions/${functionName}?Qualifier=${qualifier}`
    : `/functions/${functionName}`;
  await lambdaRequest(path, { method: 'DELETE' });
  console.log(`Function ${functionName} deleted`);
};
Enter fullscreen mode Exit fullscreen mode

関数呼び出し

同期呼び出し(リクエスト-レスポンス)

const invokeFunction = async (functionName, payload, qualifier = null) => {
  const path = qualifier
    ? `/functions/${functionName}/invocations?Qualifier=${qualifier}`
    : `/functions/${functionName}/invocations`;

  const response = await lambdaRequest(path, {
    method: 'POST',
    headers: {
      'X-Amz-Invocation-Type': 'RequestResponse',
      'X-Amz-Log-Type': 'Tail'
    },
    body: payload
  });

  const result = JSON.parse(Buffer.from(response.Payload).toString());
  const logs = Buffer.from(response.LogResult, 'base64').toString();

  return { result, logs };
};

// 使用例
const { result, logs } = await invokeFunction('order-processor', {
  orderId: 'ORD-12345',
  customerId: 'CUST-67890',
  items: [
    { sku: 'PROD-001', quantity: 2 },
    { sku: 'PROD-002', quantity: 1 }
  ]
});
console.log(`Result: ${JSON.stringify(result)}`);
console.log(`Logs:\n${logs}`);
Enter fullscreen mode Exit fullscreen mode

非同期呼び出し(ファイア・アンド・フォーゲット)

const invokeAsync = async (functionName, payload) => {
  const response = await lambdaRequest(`/functions/${functionName}/invocations`, {
    method: 'POST',
    headers: {
      'X-Amz-Invocation-Type': 'Event',
      'X-Amz-Log-Type': 'None'
    },
    body: payload
  });

  return {
    statusCode: response.StatusCode,
    executionId: response['X-Amz-Execution-Id']
  };
};

// 使用例
const result = await invokeAsync('email-sender', {
  to: 'customer@example.com',
  template: 'order-confirmation',
  data: { orderId: 'ORD-12345' }
});
console.log(`Async invocation ID: ${result.executionId}`);
Enter fullscreen mode Exit fullscreen mode

ドライラン呼び出し

const dryRunInvocation = async (functionName) => {
  const response = await lambdaRequest(`/functions/${functionName}/invocations`, {
    method: 'POST',
    headers: {
      'X-Amz-Invocation-Type': 'DryRun'
    }
  });
  return response;
};

// 使用例
try {
  await dryRunInvocation('order-processor');
  console.log('Invocation permissions OK');
} catch (error) {
  console.error('Permission denied:', error.message);
}
Enter fullscreen mode Exit fullscreen mode

呼び出しレスポンスタイプ

呼び出しタイプ 動作 ユースケース
RequestResponse 同期、結果を待機 API/CLI
Event 非同期、即時返却 イベント通知
DryRun 権限のみテスト 検証/デバッグ

バージョンとエイリアス管理

バージョンの公開

const publishVersion = async (functionName, description = null) => {
  const response = await lambdaRequest(`/functions/${functionName}/versions`, {
    method: 'POST',
    body: description ? { Description: description } : {}
  });
  return response;
};

// 使用例
const version = await publishVersion('order-processor', 'v1.2.0 - Add tax calculation');
console.log(`Published version: ${version.Version}`);
Enter fullscreen mode Exit fullscreen mode

エイリアスの作成

const createAlias = async (functionName, aliasName, version, description = null) => {
  const response = await lambdaRequest(`/functions/${functionName}/aliases`, {
    method: 'POST',
    body: {
      Name: aliasName,
      FunctionVersion: version,
      Description: description
    }
  });
  return response;
};

// 使用例
const prodAlias = await createAlias('order-processor', 'prod', '5', 'Production version');
console.log(`Alias ARN: ${prodAlias.AliasArn}`);
Enter fullscreen mode Exit fullscreen mode

ルーティング設定によるトラフィックシフト

const updateAliasWithRouting = async (functionName, aliasName, routingConfig) => {
  const response = await lambdaRequest(`/functions/${functionName}/aliases/${aliasName}`, {
    method: 'PUT',
    body: {
      RoutingConfig: {
        AdditionalVersionWeights: routingConfig
      }
    }
  });
  return response;
};

// バージョン6に10%、5に90%
await updateAliasWithRouting('order-processor', 'prod', {
  '6': 0.1
});

// 検証後100%に戻す
await updateAliasWithRouting('order-processor', 'prod', {});
Enter fullscreen mode Exit fullscreen mode

エイリアスのユースケース

エイリアス バージョン 目的
dev $LATEST 開発テスト
staging テスト済み QA検証
prod 安定版 本番
blue 現在の本番 ブルー/グリーン
green 新しいバージョン ブルー/グリーン

イベントソースマッピング

SQSトリガーの作成

const createSQSEventSource = async (functionName, queueArn, batchSize = 10) => {
  const response = await lambdaRequest('/event-source-mappings', {
    method: 'POST',
    body: {
      EventSourceArn: queueArn,
      FunctionName: functionName,
      BatchSize: batchSize,
      Enabled: true
    }
  });
  return response;
};

// 使用例
const mapping = await createSQSEventSource(
  'order-processor',
  'arn:aws:sqs:us-east-1:123456789012:orders-queue',
  10
);
console.log(`Event source created: ${mapping.UUID}`);
Enter fullscreen mode Exit fullscreen mode

DynamoDBストリームトリガーの作成

const createDynamoDBEventSource = async (functionName, streamArn, startingPosition = 'LATEST') => {
  const response = await lambdaRequest('/event-source-mappings', {
    method: 'POST',
    body: {
      EventSourceArn: streamArn,
      FunctionName: functionName,
      StartingPosition: startingPosition,
      BatchSize: 100,
      BisectBatchOnFunctionError: true,
      MaximumRetryAttempts: 3
    }
  });
  return response;
};

// 使用例
await createDynamoDBEventSource(
  'user-analytics',
  'arn:aws:dynamodb:us-east-1:123456789012:table/Users/stream/2026-03-25T00:00:00.000'
);
Enter fullscreen mode Exit fullscreen mode

イベントソースのタイプ

ソース ユースケース バッチサポート
SQS メッセージキュー あり (1-10)
Kinesis リアルタイムストリーム あり (1-10,000)
DynamoDB Streams DB変更監視 あり (1-1,000)
S3 オブジェクトイベント なし
EventBridge イベントルーティング あり
API Gateway HTTP API なし
Schedule Cronジョブ なし

レイヤー管理

レイヤーの作成

const createLayer = async (layerName, layerConfig) => {
  const response = await lambdaRequest('/layers', {
    method: 'POST',
    body: {
      LayerName: layerName,
      Description: layerConfig.description,
      CompatibleRuntimes: layerConfig.runtimes,
      Content: {
        S3Bucket: layerConfig.s3Bucket,
        S3Key: layerConfig.s3Key
      }
    }
  });
  return response;
};

// 使用例
const layer = await createLayer('shared-utils', {
  description: 'Shared utilities and dependencies',
  runtimes: ['nodejs20.x', 'nodejs18.x'],
  s3Bucket: 'my-layers-bucket',
  s3Key: 'shared-utils/v1.zip'
});
console.log(`Layer ARN: ${layer.LayerArn}`);
Enter fullscreen mode Exit fullscreen mode

関数でのレイヤーの使用

const createFunctionWithLayers = async (functionConfig) => {
  const response = await lambdaRequest('/functions', {
    method: 'POST',
    body: {
      FunctionName: functionConfig.name,
      Runtime: functionConfig.runtime,
      Role: functionConfig.roleArn,
      Handler: functionConfig.handler,
      Code: {
        S3Bucket: functionConfig.s3Bucket,
        S3Key: functionConfig.s3Key
      },
      Layers: functionConfig.layers
    }
  });
  return response;
};

// 使用例
await createFunctionWithLayers({
  name: 'api-handler',
  roleArn: 'arn:aws:iam::123456789012:role/lambda-execution-role',
  handler: 'index.handler',
  runtime: 'nodejs20.x',
  s3Bucket: 'my-deployments-bucket',
  s3Key: 'api-handler/v1.0.0.zip',
  layers: [
    'arn:aws:lambda:us-east-1:123456789012:layer:shared-utils:1',
    'arn:aws:lambda:us-east-1:123456789012:layer:aws-sdk:3'
  ]
});
Enter fullscreen mode Exit fullscreen mode

同時実行とスケーリング

予約済み同時実行数の設定

const putFunctionConcurrency = async (functionName, reservedConcurrentExecutions) => {
  const response = await lambdaRequest(`/functions/${functionName}/concurrency`, {
    method: 'PUT',
    body: {
      ReservedConcurrentExecutions: reservedConcurrentExecutions
    }
  });
  return response;
};

// 例:100スロット予約
await putFunctionConcurrency('order-processor', 100);
Enter fullscreen mode Exit fullscreen mode

アカウントの同時実行制限

アカウントタイプ デフォルト制限 増加可能
無料枠 1,000 はい
従量課金 1,000 はい
エンタープライズ 1,000以上 カスタム制限

本番デプロイチェックリスト

  • [ ] AWS SDKで自動SigV4署名
  • [ ] バージョン・エイリアス運用
  • [ ] 重要関数に予約同時実行
  • [ ] 非同期呼び出し用DLQ
  • [ ] X-Rayトレース有効化
  • [ ] VPC設定
  • [ ] 構造化ロギング(JSON)
  • [ ] CloudWatchアラーム設定
  • [ ] 共有依存にレイヤー活用
  • [ ] ブルー/グリーンデプロイ実装

実際のユースケース

APIバックエンド

  • 課題: トラフィック変動・スケーリング
  • 解決策: Lambda + API Gateway + オートスケーリング
  • 結果: 99.99%稼働・コスト60%削減

実装例:

  • リソースごとのLambda関数
  • API Gatewayでルーティング・認証
  • DynamoDBでストレージ
  • プロビジョニング同時実行

イベント処理パイプライン

  • 課題: 注文急増に耐える
  • 解決策: SQS + Lambda (バッチ処理)
  • 結果: 損失ゼロ・10倍スパイク対応

実装例:

  • SQSで注文バッファ
  • Lambdaでバッチ処理
  • DLQで失敗ハンドリング
  • CloudWatchアラート

結論

AWS Lambda APIは、サーバーレス開発・運用の自動化に最適なAPI層を提供します。

  • IAM認証+SigV4署名(AWS SDK推奨)
  • 同期・非同期呼び出し
  • バージョン・エイリアス管理
  • イベントソースマッピング
  • レイヤーによる依存共有
  • ApidogはAPIテスト・チームコラボレーションを効率化

FAQセクション

Lambda APIで認証するにはどうすればよいですか?

AWS IAM認証情報を署名バージョン4で署名して利用。AWS SDKを使うと自動で署名処理されます。

同期呼び出しと非同期呼び出しの違いは?

同期(RequestResponse)は完了まで待機し結果を返却。非同期(Event)は即レスポンス・処理はバックグラウンド。

Lambdaのバージョンはどう機能しますか?

各バージョンは不変スナップショット。エイリアスで特定バージョンにトラフィック割当可能。

Lambdaレイヤーとは?

コードや依存パッケージを分離し、複数関数で共通活用する仕組み。

コールドスタートを減らすには?

プロビジョニング同時実行、デプロイパッケージ軽量化、Go/Rust等の言語利用が有効。

予約済み同時実行数とは?

関数ごとに最低実行スロットを保証し、他関数の影響を受けず安定稼働。

S3からLambdaをトリガーできますか?

はい。S3イベント通知でオブジェクト生成/削除時にLambda呼び出し可能です。

Top comments (0)