English

AWS EmulatorでAPI Gatewayの使用量プランを試す方法

​​AWS Emulator​Amazon API Gateway,AWS CLI,curl

API Gateway の REST API に、API キーと使用量プランを AWS Emulator の上で設定しました。キーのないリクエストは 403、上限を超えたリクエストは 429 で断られるところを、手元で確かめられます。AWS のアカウントは要りません。Web API を利用者ごとに API キーで見分けて、1日の回数制限や秒あたりのレート制限(スロットリング)をかけたいときに、本物の AWS で作る前に設定の組み立てを試せます。コマンドと出力をそのまま載せます。

補足

検証環境は Ubuntu 24.04.5(x86_64)、AWS Emulator 1.0.602(2026年11月24日リリース、Debian パッケージ)、AWS CLI 2.42.2、curl 8.5.0 です。AWS のアカウントと認証情報は使っていません。本物の API Gateway での動き(キーを使用量プランに入れてから効くまでの時間、上限の正確さ、断られたリクエストを get-usage でどう数えるか)と料金は確かめておらず、本物について書いているところは公式ドキュメントを出どころにしています。Lambda 関数をつないだ API、Lambda オーソライザーからキーを渡す方法(AUTHORIZER)、メソッドごとの上限、キーの読み込み(インポート)は試していません。AWS Emulator の公式ドキュメントによると、AWS がエミュレーターの動きを本物と照らし合わせているのは、米国西部(オレゴン、us-west-2)リージョンだけです(グローバルなサービスは us-east-1)。この記事は、公式ドキュメントの環境変数の例のとおり us-east-1 を使いました。

API キーを使えるのは REST API だけ

API Gateway には REST API と HTTP API の2種類があります。REST API と HTTP API の違いの説明にある表では、API キーと、利用者ごとの上限(使用量プラン)が使えるのは REST API だけです。AWS CLI では、aws apigatewayv2 ではなく aws apigateway のほうで作ります。HTTP API と Lambda 関数をつなぐ手順は、別の記事「AWS EmulatorでAPI GatewayからLambdaを呼ぶ方法」に書きました。

使用量プランと API キーの説明によると、仕組みは次のとおりです。

  • API キー:利用者に配る英数字の文字列。リクエストのたびに送ってもらい、誰からのリクエストかを見分ける
  • 使用量プラン:どの API のどのステージを、どのキーで呼べるかを決め、秒あたりの上限(スロットリング)と、期間ごとの回数の上限(クォータ)を付けられる

エミュレーターを起動して、AWS CLI を向ける

AWS Emulator は、公式ガイドにある Linux での入れ方のとおりに、Debian パッケージの署名を gpg で確かめてから入れました。aws-emulator -t off で起動します。-t off は、利用状況のデータ(テレメトリー)を送らない指定です。

エミュレーターを動かしたまま、別の端末で、SDK の接続先をエミュレーターに向ける手順にある環境変数を設定します。最後の AWS_PAGER は、AWS CLI の出力をページャーで開かずに表示するために足しました。

bash
export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/emulator/9297/emulator_credentials
export AWS_CONFIG_FILE=~/.aws/emulator/9297/config
export AWS_CA_BUNDLE=~/.aws/emulator/9297/ca.pem
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE
export AWS_PAGER=""

起動した直後は、REST API も API キーも使用量プランもありません。

text
$ aws apigateway get-rest-apis
{
    "items": []
}
$ aws apigateway get-api-keys
{
    "items": []
}
$ aws apigateway get-usage-plans
{
    "items": []
}

キーが必要な GET /items と、要らない GET /health を作る

試すための REST API に、2つのメソッドを作ります。GET /items はキーが必要で、GET /health はキーなしで呼べます。裏の処理は用意せず、API Gateway が決まった応答を返す MOCK のインテグレーションにしました。

text
$ aws apigateway create-rest-api --name example-keys-api --endpoint-configuration types=REGIONAL --query "{id:id,name:name,apiKeySource:apiKeySource}"
{
    "id": "1g5ik3wi7e",
    "name": "example-keys-api",
    "apiKeySource": "HEADER"
}

apiKeySource が HEADER なので、キーはリクエストの X-API-Key ヘッダーで受け取ります(API キーの受け取り方の説明)。

ここからは、API の ID を $API、ルート(/)、/items、/health のリソースの ID を $ROOT、$ITEMS、$HEALTH という変数に入れて使います。$API と $ROOT は、次のように取り出しました($ITEMS と $HEALTH も、リソースを作ったあとに同じ形で path を変えて取り出しています)。

bash
API=$(aws apigateway get-rest-apis --query 'items[0].id' --output text)
ROOT=$(aws apigateway get-resources --rest-api-id $API --query 'items[?path==`/`].id' --output text)

リソースは create-resource で作りました。

text
$ aws apigateway create-resource --rest-api-id $API --parent-id $ROOT --path-part items --query "[id,path]" --output text
b508k4	/items
$ aws apigateway create-resource --rest-api-id $API --parent-id $ROOT --path-part health --query "[id,path]" --output text
np02uv	/health

キーを必須にするのは、put-method の --api-key-required です(メソッドでキーを必須にする説明)。付けなかった /health は apiKeyRequired が false になりました。

text
$ aws apigateway put-method --rest-api-id $API --resource-id $ITEMS --http-method GET --authorization-type NONE --api-key-required
{
    "httpMethod": "GET",
    "authorizationType": "NONE",
    "apiKeyRequired": true
}
$ aws apigateway put-method --rest-api-id $API --resource-id $HEALTH --http-method GET --authorization-type NONE
{
    "httpMethod": "GET",
    "authorizationType": "NONE",
    "apiKeyRequired": false
}

2つのメソッドに MOCK のインテグレーションとメソッドの応答を付け、/items は {"items": ["tama", "mike"]}、/health は {"status": "ok"} を返すようにしました。

text
$ for r in $ITEMS $HEALTH; do aws apigateway put-integration --rest-api-id $API --resource-id $r --http-method GET --type MOCK --request-templates "{\"application/json\":\"{\\\"statusCode\\\": 200}\"}" --query type --output text; aws apigateway put-method-response --rest-api-id $API --resource-id $r --http-method GET --status-code 200 --query statusCode --output text; done
MOCK
200
MOCK
200
$ aws apigateway put-integration-response --rest-api-id $API --resource-id $ITEMS --http-method GET --status-code 200 --response-templates "{\"application/json\":\"{\\\"items\\\": [\\\"tama\\\", \\\"mike\\\"]}\"}" --query responseTemplates
{
    "application/json": "{\"items\": [\"tama\", \"mike\"]}"
}
$ aws apigateway put-integration-response --rest-api-id $API --resource-id $HEALTH --http-method GET --status-code 200 --response-templates "{\"application/json\":\"{\\\"status\\\": \\\"ok\\\"}\"}" --query responseTemplates
{
    "application/json": "{\"status\": \"ok\"}"
}

REST API は、デプロイしてステージを作るまで呼べません(REST API の呼び出し方の説明)。dev というステージにデプロイします。

text
$ aws apigateway create-deployment --rest-api-id $API --stage-name dev --query "{id:id}"
{
    "id": "g45hf8"
}

キーなしで呼ぶと、キーが必要なほうだけ 403 になる

エミュレーターでは、https://127.0.0.1:9297/_aws/execute-api/<API の ID>/dev が、ステージ dev の URL になりました。この URL を $U に入れて(U="https://127.0.0.1:9297/_aws/execute-api/$API/dev")、curl で呼びます。--cacert は、エミュレーターが作った証明書を curl に信頼させる指定です。本物の AWS では、公式ドキュメントのとおり https://<API の ID>.execute-api.<リージョン>.amazonaws.com/<ステージ>/ の形になります。

text
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem $U/health
HTTP/1.1 200 OK
content-type: application/json
content-length: 16
x-amzn-requestid: 2e680c25-52ea-4eb3-9862-6c1f91e879f8
x-amz-apigw-id: 4279ac9b-767e-4138-835a-0f57c33a8d0b
date: Tue, 24 Nov 2026 13:18:18 GMT

{"status": "ok"}
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem $U/items
HTTP/1.1 403 Forbidden
content-type: application/json
content-length: 23
x-amzn-errortype: ForbiddenException
x-amzn-requestid: 9d9cd9d7-a640-41f5-8715-e321b616b14c
x-amz-apigw-id: 13ce34fe-12f0-4dbf-a65c-f1123bc02734
date: Tue, 24 Nov 2026 13:18:18 GMT

{"message":"Forbidden"}

記事に載せた curl のコマンドでは、出力の最後に改行を足すために付けた ; echo を省いています。

キーを作っただけでは、まだ 403 のまま

create-api-key でキーを作ります。値はエミュレーターが作りました。

text
$ aws apigateway create-api-key --name example-key-a --enabled
{
    "id": "uptb7bzjre",
    "value": "d7fwkZIEgeW850Es6m6ItRXIGkHLRZXb6DVydQzj",
    "name": "example-key-a",
    "enabled": true,
    "createdDate": "2026-11-24T13:18:18+00:00",
    "lastUpdatedDate": "2026-11-24T13:18:18+00:00",
    "stageKeys": [],
    "tags": {}
}

キーには、管理用の id と、利用者に渡す value の2つがあります。一覧の get-api-keys では value は null で、値を見るには get-api-key に --include-value を付けました。

text
$ aws apigateway get-api-keys --query "items[].{id:id,name:name,value:value}"
[
    {
        "id": "uptb7bzjre",
        "name": "example-key-a",
        "value": null
    }
]
$ aws apigateway get-api-key --api-key $KA --include-value --query "{id:id,value:value}"
{
    "id": "uptb7bzjre",
    "value": "d7fwkZIEgeW850Es6m6ItRXIGkHLRZXb6DVydQzj"
}

キーの id を $KA、value を $VA に入れます。

bash
KA=$(aws apigateway get-api-keys --name-query example-key-a --query 'items[0].id' --output text)
VA=$(aws apigateway get-api-key --api-key $KA --include-value --query value --output text)

x-api-key ヘッダーに値を付けて呼ぶと、まだ 403 でした。

text
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem -H "x-api-key: $VA" $U/items
HTTP/1.1 403 Forbidden
content-type: application/json
content-length: 23
x-amzn-errortype: ForbiddenException
x-amzn-requestid: bfc3fd72-3c79-4d4b-818c-e3f2a400addb
x-amz-apigw-id: cbf0a506-2f4c-4f5c-bccd-5337ab49a3d0
date: Tue, 24 Nov 2026 13:18:21 GMT

{"message":"Forbidden"}

API キーの設定の説明にも、キーを作ったら使用量プランに入れる必要がある、と書かれています。API Gateway は、届いたキーを使用量プランの中のキーと照らし合わせ、見つからなければ 403 を返します(API キーの受け取り方の説明)。

1日3回までの使用量プランに入れて、上限を超えさせる

create-usage-plan で、ステージ dev を対象に、回数の上限(--quota)だけを付けたプランを作ります。1日(DAY)に3回までです。

text
$ aws apigateway create-usage-plan --name example-quota-plan --api-stages apiId=$API,stage=dev --quota limit=3,period=DAY
{
    "id": "l67rlhxwfm",
    "name": "example-quota-plan",
    "apiStages": [
        {
            "apiId": "1g5ik3wi7e",
            "stage": "dev"
        }
    ],
    "quota": {
        "limit": 3,
        "offset": 0,
        "period": "DAY"
    },
    "tags": {}
}

プランの ID を $PQ に入れ、create-usage-plan-key でキー A をプランに入れます。

bash
PQ=$(aws apigateway get-usage-plans --query 'items[?name==`example-quota-plan`].id' --output text)
text
$ aws apigateway create-usage-plan-key --usage-plan-id $PQ --key-id $KA --key-type API_KEY --query "{id:id,type:type,name:name}"
{
    "id": "uptb7bzjre",
    "type": "API_KEY",
    "name": "example-key-a"
}

同じキーで呼ぶと、今度は 200 が返りました。エミュレーターでは、プランに入れた直後に呼んで、もう通っています。本物の API Gateway では、公式ドキュメントに、キーをプランに入れる更新は終わるまで数分かかることがある、と書かれています。

text
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem -H "x-api-key: $VA" $U/items
HTTP/1.1 200 OK
content-type: application/json
content-length: 27
x-amzn-requestid: f95b6ed7-5e6f-497c-9aa2-8b57e2045431
x-amz-apigw-id: bce30028-6ff2-4987-830e-7a70a23e5d41
date: Tue, 24 Nov 2026 13:18:23 GMT

{"items": ["tama", "mike"]}

どのキーとも合わない値を送ると、403 でした。

text
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem -H "x-api-key: wrong-key-value-0000000000" $U/items
HTTP/1.1 403 Forbidden
content-type: application/json
content-length: 23
x-amzn-errortype: ForbiddenException
x-amzn-requestid: 72d32e84-83a0-480d-8022-5e8cb130c39a
x-amz-apigw-id: 750c4698-cfae-49bf-bbfc-4bc75392dbd4
date: Tue, 24 Nov 2026 13:18:23 GMT

{"message":"Forbidden"}

続けて、1.5秒おきに4回呼びました。1回目と合わせて3回までが 200 で、4回目から 429 になりました。

text
$ for i in 2 3 4 5; do echo "$i 回目: $(curl -s -o /dev/null -w "%{http_code}" --cacert ~/.aws/emulator/9297/ca.pem -H "x-api-key: $VA" $U/items)"; sleep 1.5; done
2 回目: 200
3 回目: 200
4 回目: 429
5 回目: 429
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem -H "x-api-key: $VA" $U/items
HTTP/1.1 429 Too Many Requests
content-type: application/json
content-length: 28
x-amzn-errortype: LimitExceededException
x-amzn-requestid: b106de3d-230b-415d-bdb0-a463659861a8
x-amz-apigw-id: aadc42d9-133b-4090-94cb-256328436acc
date: Tue, 24 Nov 2026 13:18:29 GMT

{"message":"Limit Exceeded"}

上限に当たったあとも、キーの要らない /health は同じキーを付けて呼んでも 200 でした。

text
$ curl -s -o /dev/null -w "%{http_code}\n" --cacert ~/.aws/emulator/9297/ca.pem -H "x-api-key: $VA" $U/health
200

get-usage で、使った回数と残りを見る

get-usage で、キーごとの1日の使用量を見られます。中の配列は [使った回数, 残りの回数] です(get-usage のリファレンス)。断られた4回目と5回目、中身を見るために -si で送った1回は数えられず、[3, 0] でした。

text
$ aws apigateway get-usage --usage-plan-id $PQ --start-date $(date -u +%F) --end-date $(date -u +%F)
{
    "items": {
        "uptb7bzjre": [
            [
                3,
                0
            ]
        ]
    },
    "usagePlanId": "l67rlhxwfm",
    "startDate": "2026-11-24",
    "endDate": "2026-11-24"
}

update-usage で、残りの回数を変える

update-usage は、今の期間の残りの回数を、そのキーだけ一時的に変えるコマンドです。残りを2回にすると、2回は 200 になり、3回目でまた 429 になりました。

text
$ aws apigateway update-usage --usage-plan-id $PQ --key-id $KA --patch-operations op=replace,path=/remaining,value=2
{
    "usagePlanId": "l67rlhxwfm",
    "startDate": "2026-11-24",
    "endDate": "2026-11-24",
    "items": {
        "uptb7bzjre": [
            [
                3,
                2
            ]
        ]
    }
}
$ for i in 1 2 3; do echo "$i 回目: $(curl -s -o /dev/null -w "%{http_code}" --cacert ~/.aws/emulator/9297/ca.pem -H "x-api-key: $VA" $U/items)"; sleep 1.5; done
1 回目: 200
2 回目: 200
3 回目: 429

秒あたりの上限は、続けて送ったときだけ 429 になる

秒あたりの上限は、リクエストのスロットリングの説明にあるトークンバケットの考え方で決まります。rateLimit は1秒あたりにトークン(1リクエスト分)を足す数、burstLimit はバケットの大きさです。

1日の上限と混ざらないように、2つ目のキー example-key-b を作り(id を $KB、値を $VB に、キー A と同じ形で入れました)、rateLimit 1、burstLimit 2 だけを付けた別のプランに入れました(プランの ID は $PT に入れました)。

text
$ aws apigateway create-usage-plan --name example-throttle-plan --api-stages apiId=$API,stage=dev --throttle burstLimit=2,rateLimit=1
{
    "id": "dq1mz8i5hv",
    "name": "example-throttle-plan",
    "apiStages": [
        {
            "apiId": "1g5ik3wi7e",
            "stage": "dev"
        }
    ],
    "throttle": {
        "burstLimit": 2,
        "rateLimit": 1.0
    },
    "tags": {}
}
$ aws apigateway create-usage-plan-key --usage-plan-id $PT --key-id $KB --key-type API_KEY --query "{id:id,type:type,name:name}"
{
    "id": "3ufifeqn4c",
    "type": "API_KEY",
    "name": "example-key-b"
}

待たずに6回続けて送ると、burstLimit の2回までが 200 で、3回目から 429 になりました。行の先頭は送った時刻(UTC)です。

text
$ for i in 1 2 3 4 5 6; do echo "$(date -u +%T.%N | cut -c1-12) $i 回目: $(curl -s -o /dev/null -w "%{http_code}" --cacert ~/.aws/emulator/9297/ca.pem -H "x-api-key: $VB" $U/items)"; done
13:18:39.755 1 回目: 200
13:18:39.765 2 回目: 200
13:18:39.775 3 回目: 429
13:18:39.785 4 回目: 429
13:18:39.794 5 回目: 429
13:18:39.804 6 回目: 429

同じ 429 でも、1日の上限のときとは本文と x-amzn-errortype が違い、Too Many Requests と TooManyRequestsException でした。

text
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem -H "x-api-key: $VB" $U/items
HTTP/1.1 429 Too Many Requests
content-type: application/json
content-length: 31
x-amzn-errortype: TooManyRequestsException
x-amzn-requestid: 872ecd4a-5133-41ce-b2eb-313a7fce2d12
x-amz-apigw-id: ea072cae-7290-4e69-abdc-bf3e88d0f1b5
date: Tue, 24 Nov 2026 13:18:39 GMT

{"message":"Too Many Requests"}

3秒待ってから、1.1秒おきに6回送ると、すべて 200 でした。1秒に1回より少し遅いので、トークンが足りなくなりません。

text
$ sleep 3; for i in 1 2 3 4 5 6; do echo "$(date -u +%T.%N | cut -c1-12) $i 回目: $(curl -s -o /dev/null -w "%{http_code}" --cacert ~/.aws/emulator/9297/ca.pem -H "x-api-key: $VB" $U/items)"; sleep 1.1; done
13:18:42.869 1 回目: 200
13:18:43.982 2 回目: 200
13:18:45.136 3 回目: 200
13:18:46.249 4 回目: 200
13:18:47.363 5 回目: 200
13:18:48.477 6 回目: 200

このプランの get-usage は [13, 0] でした。13 は、ここまでにキー B で送った回数(200 の8回と、429 の5回)の合計です。回数の上限で断られた分は数えられなかったのに対して、秒あたりの上限で断られた分は数えられていました。このプランには回数の上限を付けていませんが、残りは 0 と出ています。

text
$ aws apigateway get-usage --usage-plan-id $PT --start-date $(date -u +%F) --end-date $(date -u +%F)
{
    "items": {
        "3ufifeqn4c": [
            [
                13,
                0
            ]
        ]
    },
    "usagePlanId": "dq1mz8i5hv",
    "startDate": "2026-11-24",
    "endDate": "2026-11-24"
}

キーを無効にすると、プランに入っていても 403 になる

update-api-key で enabled を false にすると、キー B は 403 になりました。true に戻すと、また 200 で呼べました。

text
$ aws apigateway update-api-key --api-key $KB --patch-operations op=replace,path=/enabled,value=false --query "{name:name,enabled:enabled}"
{
    "name": "example-key-b",
    "enabled": false
}
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem -H "x-api-key: $VB" $U/items
HTTP/1.1 403 Forbidden
content-type: application/json
content-length: 23
x-amzn-errortype: ForbiddenException
x-amzn-requestid: 95ab27a9-4a15-4cd8-82b6-995c87611aac
x-amz-apigw-id: 0bd931de-d36b-46ce-8437-7ce8757149d3
date: Tue, 24 Nov 2026 13:18:50 GMT

{"message":"Forbidden"}
$ aws apigateway update-api-key --api-key $KB --patch-operations op=replace,path=/enabled,value=true --query "{name:name,enabled:enabled}"
{
    "name": "example-key-b",
    "enabled": true
}
$ sleep 2; curl -s -o /dev/null -w "%{http_code}\n" --cacert ~/.aws/emulator/9297/ca.pem -H "x-api-key: $VB" $U/items
200

ここまでの結果を、1枚にまとめました。

GET /items に送ったときの応答のまとめ。x-api-key ヘッダーなし、どの使用量プランにも入っていないキー、存在しない値のキー、無効にしたキーは 403 Forbidden。使用量プランに入れたキーは 200 OK。1日の回数の上限を超えると 429 Limit Exceeded、秒あたりの上限を超えると 429 Too Many Requests
キーの状態と上限ごとに、エミュレーターが返したステータスと、エラーのときの本文の message

API Gateway の応答の種類の一覧では、キーが正しくないとき(INVALID_API_KEY)は 403、回数の上限を超えたとき(QUOTA_EXCEEDED)と秒あたりの上限を超えたとき(THROTTLED)は 429 が既定です。エミュレーターが返したステータスは、この表と同じでした。

注意

使用量プランと API キーのベストプラクティスには、API キーを認証や認可(誰に API を使わせるかの制御)に使わないように、と書かれています。同じプランに複数の API があると、1つの API 用のキーで、プランの中のすべての API を呼べるためです。アクセスの制御には、IAM ロール、Lambda オーソライザー、Amazon Cognito のユーザープールを使うように案内されています。また、同じページの使用量プランと API キーの説明には、スロットリングとクォータは確実な上限ではなく、利用者が上限を超えることがあるので、料金を抑える手段やアクセスを止める手段として頼らないように、とも書かれています。

使用量プランは、ステージを外してから消す

片付けで delete-usage-plan を実行すると、API のステージが結び付いているので消せない、というエラーになりました。

text
$ aws apigateway delete-usage-plan --usage-plan-id $PQ

aws: [ERROR]: An error occurred (BadRequestException) when calling the DeleteUsagePlan operation: Cannot delete Usage Plan l67rlhxwfm because there are API Stages associated with it, including 1g5ik3wi7e:dev

update-usage-plan で /apiStages から dev を外すと、消せました。そのあとで、キーと REST API も消しています。

text
$ for p in $PQ $PT; do aws apigateway update-usage-plan --usage-plan-id $p --patch-operations op=remove,path=/apiStages,value=$API:dev --query "{name:name,apiStages:apiStages}"; aws apigateway delete-usage-plan --usage-plan-id $p; done; aws apigateway get-usage-plans
{
    "name": "example-quota-plan",
    "apiStages": []
}
{
    "name": "example-throttle-plan",
    "apiStages": []
}
{
    "items": []
}
$ for k in $KA $KB; do aws apigateway delete-api-key --api-key $k; done; aws apigateway delete-rest-api --rest-api-id $API; aws apigateway get-api-keys; aws apigateway get-rest-apis
{
    "items": []
}
{
    "items": []
}

AWS Emulator の制限の説明にあるとおり、エミュレーターは作ったリソースをメモリーに置き、止めると消します。API キーや使用量プラン、使った回数も、エミュレーターを止めると残りません。

​Posted by 86