API Gateway + Lambda で REST API を構築する【AWS SAM ハンズオン】

概要

Amazon API Gateway(REST API)と AWS Lambda、DynamoDB を組み合わせて、アイテムを CRUD する小さな REST API を作ります。

  • インフラは AWS SAM のテンプレート1枚で定義します
  • Lambda は Python 3.12 で書き、Lambda プロキシ統合で API Gateway とつなぎます
  • デプロイ後に curl で動作を確認し、最後にスタックごと削除します
メソッド パス 内容
GET /items 一覧取得
POST /items 新規作成
GET /items/{id} 1件取得
PUT /items/{id} 更新
DELETE /items/{id} 削除

> 注意:このハンズオンの API は認証なしで公開されます。検証が終わったら必ず sam delete で削除してください。

環境

  • AWS アカウント(IAM の作成権限を持つユーザーかロール)
  • AWS CLI v2(認証設定済み)
  • AWS SAM CLI
  • Python 3.12
  • curl / jq

リージョンは ap-northeast-1 を例にします。

構成

クライアント (curl)
   │  HTTPS
   ▼
API Gateway (REST API / ステージ: dev)
   │  Lambda プロキシ統合
   ▼
Lambda (Python 3.12, arm64)
   │  boto3
   ▼
DynamoDB (オンデマンド)

REST API と HTTP API の違い

観点 REST API HTTP API
料金・レイテンシ 比較的高い 安く、軽量
API キー・使用量プラン あり なし
リクエスト検証 あり なし
AWS WAF 連携 あり なし
レスポンスキャッシュ あり なし
プライベートエンドポイント あり なし

Lambda を呼ぶだけで JWT 認証があれば十分なら、HTTP API で足ります。使用量プランや WAF が必要な場合は REST API を選びます。この記事では REST API を使います。

手順

1. ディレクトリを作る

mkdir items-api && cd items-api
mkdir src
items-api/
├── template.yaml
└── src/
    └── app.py

2. SAM テンプレートを書く

template.yaml

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Items REST API (API Gateway + Lambda + DynamoDB)

Globals:
  Function:
    Runtime: python3.12
    Architectures: [arm64]
    Timeout: 10
    MemorySize: 256

Resources:
  ItemsApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: dev
      MethodSettings:
        - ResourcePath: "/*"
          HttpMethod: "*"
          ThrottlingRateLimit: 10
          ThrottlingBurstLimit: 20

  ItemsFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: app.handler
      Environment:
        Variables:
          TABLE_NAME: !Ref ItemsTable
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref ItemsTable
      Events:
        ListItems:
          Type: Api
          Properties:
            RestApiId: !Ref ItemsApi
            Path: /items
            Method: get
        CreateItem:
          Type: Api
          Properties:
            RestApiId: !Ref ItemsApi
            Path: /items
            Method: post
        GetItem:
          Type: Api
          Properties:
            RestApiId: !Ref ItemsApi
            Path: /items/{id}
            Method: get
        UpdateItem:
          Type: Api
          Properties:
            RestApiId: !Ref ItemsApi
            Path: /items/{id}
            Method: put
        DeleteItem:
          Type: Api
          Properties:
            RestApiId: !Ref ItemsApi
            Path: /items/{id}
            Method: delete

  ItemsTable:
    Type: AWS::DynamoDB::Table
    Properties:
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      KeySchema:
        - AttributeName: id
          KeyType: HASH

Outputs:
  ApiUrl:
    Description: API endpoint
    Value: !Sub "https://${ItemsApi}.execute-api.${AWS::Region}.amazonaws.com/dev"

ポイント:

  • Events の Type: Api を書くと、SAM がリソース・メソッド・Lambda プロキシ統合に加えて、API Gateway から Lambda を呼ぶ権限まで作ります。手作業では最も抜けやすい部分です。
  • DynamoDBCrudPolicy で、権限を対象テーブルだけに絞れます。
  • MethodSettings のスロットリングは、意図しない大量アクセスへの保険です。

3. Lambda 関数を書く

src/app.py

import json
import logging
import os
import uuid
from decimal import Decimal

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger()
logger.setLevel(logging.INFO)

# コールドスタート時に1回だけ初期化し、ウォームな実行では再利用する
table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])


def _json_default(o):
    # DynamoDB の数値は Decimal で返るため、JSON 化できる型に変換する
    if isinstance(o, Decimal):
        return int(o) if o == o.to_integral_value() else float(o)
    raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")


def response(status, body=None):
    # プロキシ統合のレスポンス形式: statusCode / headers / body(文字列)
    return {
        "statusCode": status,
        "headers": {"Content-Type": "application/json"},
        "body": "" if body is None else json.dumps(body, ensure_ascii=False, default=_json_default),
    }


def parse_body(event):
    raw = event.get("body") or "{}"
    # float のままだと DynamoDB に書き込めないので Decimal で受ける
    return json.loads(raw, parse_float=Decimal)


def validate(body):
    name = body.get("name")
    if not isinstance(name, str) or not name.strip():
        return "name is required"
    price = body.get("price", 0)
    if isinstance(price, bool) or not isinstance(price, (int, Decimal)) or price < 0:
        return "price must be a non-negative number"
    return None


def list_items():
    # Scan は全件読むので、本番ではクエリ設計を見直すこと
    res = table.scan(Limit=100)
    return response(200, {"items": res.get("Items", [])})


def create_item(body):
    error = validate(body)
    if error:
        return response(400, {"message": error})
    item = {"id": str(uuid.uuid4()), "name": body["name"], "price": body.get("price", 0)}
    table.put_item(Item=item)
    return response(201, item)


def get_item(item_id):
    item = table.get_item(Key={"id": item_id}).get("Item")
    if item is None:
        return response(404, {"message": "not found"})
    return response(200, item)


def update_item(item_id, body):
    error = validate(body)
    if error:
        return response(400, {"message": error})
    try:
        res = table.update_item(
            Key={"id": item_id},
            # name は DynamoDB の予約語なのでプレースホルダで書く
            UpdateExpression="SET #n = :name, price = :price",
            ExpressionAttributeNames={"#n": "name"},
            ExpressionAttributeValues={":name": body["name"], ":price": body.get("price", 0)},
            ConditionExpression="attribute_exists(id)",
            ReturnValues="ALL_NEW",
        )
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            return response(404, {"message": "not found"})
        raise
    return response(200, res["Attributes"])


def delete_item(item_id):
    try:
        table.delete_item(Key={"id": item_id}, ConditionExpression="attribute_exists(id)")
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            return response(404, {"message": "not found"})
        raise
    return response(204)


def handler(event, context):
    method = event["httpMethod"]
    resource = event["resource"]  # 例: "/items/{id}"(実パスではなくテンプレート)
    item_id = (event.get("pathParameters") or {}).get("id")

    try:
        if resource == "/items" and method == "GET":
            return list_items()
        if resource == "/items" and method == "POST":
            return create_item(parse_body(event))
        if resource == "/items/{id}" and method == "GET":
            return get_item(item_id)
        if resource == "/items/{id}" and method == "PUT":
            return update_item(item_id, parse_body(event))
        if resource == "/items/{id}" and method == "DELETE":
            return delete_item(item_id)
        return response(405, {"message": "method not allowed"})
    except json.JSONDecodeError:
        return response(400, {"message": "invalid JSON"})
    except Exception:
        # 詳細は CloudWatch Logs にだけ残し、クライアントには返さない
        logger.exception("unhandled error")
        return response(500, {"message": "internal server error"})

コードで押さえておきたい点:

  • event["resource"](テンプレート上のパス)で分岐すると、ルーティングがシンプルになります。
  • DynamoDB の数値は、書き込み時に parse_float=Decimal で受け、読み出し時に default で数値に戻します。
  • 存在チェックは ConditionExpression="attribute_exists(id)" の条件付き書き込みで行い、失敗したら 404 を返します。
  • name は DynamoDB の予約語なので、#n プレースホルダで指定します。

4. ビルドとデプロイ

sam build
sam deploy --guided

対話プロンプトへの回答例です。

  • Stack Name: items-api
  • AWS Region: ap-northeast-1
  • Confirm changes before deploy: y
  • Allow SAM CLI IAM role creation: Y
  • ItemsFunction has no authentication. Is this okay?: 検証用なので y(イベントごとに聞かれます)
  • Save arguments to configuration file: Y

エンドポイントは次のコマンドで確認できます。

sam list stack-outputs --stack-name items-api --output json

確認方法

export API_URL="https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/dev"

# 作成(201)
curl -s -X POST "$API_URL/items" \
  -H "Content-Type: application/json" \
  -d '{"name": "keyboard", "price": 12800}' | jq

次のような JSON が返ります(id は実行ごとに変わります)。

{
  "id": "6f1c2c1e-....",
  "name": "keyboard",
  "price": 12800
}
# 一覧・1件取得
curl -s "$API_URL/items" | jq
export ITEM_ID="(作成時に返った id)"
curl -s "$API_URL/items/$ITEM_ID" | jq

# 更新(小数も可)
curl -s -X PUT "$API_URL/items/$ITEM_ID" \
  -H "Content-Type: application/json" \
  -d '{"name": "keyboard (JIS)", "price": 13800.5}' | jq

# 削除(204)→ 再取得(404)
curl -s -o /dev/null -w "%{http_code}\n" -X DELETE "$API_URL/items/$ITEM_ID"
curl -s -o /dev/null -w "%{http_code}\n" "$API_URL/items/$ITEM_ID"

# バリデーションエラー(400)
curl -s -X POST "$API_URL/items" -H "Content-Type: application/json" -d '{"price": -1}'

# ログの確認
sam logs --stack-name items-api --name ItemsFunction --tail

つまずきやすいポイント

403 Missing Authentication Token

名前に反して、認証とは関係なく存在しないパス・メソッドを叩いたときに出ることが多いエラーです。URL にステージ名(/dev)が入っているか、パスのスペルやメソッドが正しいかを確認してください。

502 Internal server error

Lambda の戻り値がプロキシ統合の形式になっていないと出ます。statusCode があるか、body が文字列になっているか(dict のままだと NG)、未処理の例外が起きていないかを確認してください。

Decimal / float のエラー

boto3 の resource API は DynamoDB の数値を Decimal で返すため、json.dumps で変換しないと落ちます。逆に float は書き込めません。読み書きの両方で対処が必要です。

CORS エラー

プロキシ統合では、Lambda が返すレスポンスに Access-Control-Allow-Origin などを含める必要があります。プリフライト(OPTIONS)への応答は、AWS::Serverless::Api の Cors プロパティで設定します。

タイムアウト

REST API の統合タイムアウトはデフォルトで 29 秒です。重い処理は SQS などで非同期化します。

注意点

  • 認可:本番では Cognito オーソライザー、IAM 認可、Lambda オーソライザーのいずれかを設定します。API キーは認証の代わりになりません。
  • Scan を避ける:アクセスパターンに合わせてキーや GSI を設計します。
  • エラー詳細を返さない:スタックトレースはログにだけ残します。
  • ログ保持期間:デフォルトは無期限です。AWS::Logs::LogGroup で RetentionInDays を設定します。
  • 費用:いずれも従量課金です。検証環境を放置しないようにしましょう。

片付け

sam delete --stack-name items-api

API・Lambda・DynamoDB テーブル(中のデータも含む)がまとめて削除されます。

まとめ

  • SAM の Events: Type: Api で、ルーティング・統合・実行権限まで一括で定義できる
  • プロキシ統合の戻り値は「statusCode + 文字列の body」。崩れると 502 になる
  • Python × DynamoDB では Decimal の扱いを最初に決める
  • 403 Missing Authentication Token は、まずパスとステージ名を疑う
  • REST API と HTTP API は要件で選ぶ

次のステップとしては、Cognito オーソライザーによる認可、Powertools for AWS Lambda(Python)でのルーティングと構造化ログ、GitHub Actions からの sam deploy 自動化がおすすめです。

\ 最新情報をチェック /

コメントを残す

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください。