日本語

Testing API Gateway Usage Plans and API Keys with AWS Emulator

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

I set up API keys and a usage plan on a REST API in AWS Emulator. I confirmed that requests without a key get 403 and requests over the limit get 429. You do not need an AWS account. If you want to tell apart the consumers of a Web API by their API keys and apply a daily quota or a per-second rate limit (throttling), you can check the configuration locally before you build it on real AWS. The commands and their output are shown as-is.

Note

The test environment was Ubuntu 24.04.5 (x86_64), AWS Emulator 1.0.602 (released November 24, 2026, Debian package), AWS CLI 2.42.2, and curl 8.5.0. I did not use an AWS account or credentials. I did not test how real API Gateway behaves (how long a key takes to take effect after it is added to a usage plan, how accurate the limits are, or how requests that were rejected show up in get-usage), and I did not check its pricing. Where I describe the real service, I am relying on the official documentation. I did not test APIs connected to Lambda functions, passing keys from a Lambda authorizer (AUTHORIZER), per-method limits, or importing keys. According to the official AWS Emulator documentation, AWS checks the emulator's behavior against the real service only in the US West (Oregon, us-west-2) Region (global services use us-east-1). This article used us-east-1, as in the environment variable examples in the official documentation.

Only REST APIs support API keys

API Gateway has two kinds of APIs: REST APIs and HTTP APIs. In the comparison of REST APIs and HTTP APIs, only REST APIs support API keys and per-consumer limits (usage plans). With the AWS CLI, you create these with aws apigateway, not aws apigatewayv2. I covered connecting an HTTP API to a Lambda function in a separate article, "How to Call Lambda from API Gateway with AWS Emulator."

According to the explanation of usage plans and API keys, the mechanism works as follows:

  • API key: An alphanumeric string that you give to consumers. They send it with each request so you can tell who is calling.
  • Usage plan: Defines which stages of which APIs can be called with which keys. You can attach a per-second limit (throttling) and a limit on the number of calls per period (quota).

Start the emulator and point the AWS CLI at it

I installed AWS Emulator by following the official Linux installation guide, verifying the Debian package signature with gpg first. I started it with aws-emulator -t off. -t off disables sending usage data (telemetry).

With the emulator still running, I set the environment variables from the guide to pointing an SDK at the emulator in a separate terminal. I added the last line, AWS_PAGER, so that AWS CLI output is printed directly instead of opening in a pager.

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=""

Right after startup, there are no REST APIs, API keys, or usage plans.

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

Create GET /items, which requires a key, and GET /health, which does not

I created two methods on a test REST API. GET /items requires a key, and GET /health can be called without one. I did not write any backend code. Instead, I used MOCK integrations, in which API Gateway returns a fixed response.

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"
}

Because apiKeySource is HEADER, the key is read from the X-API-Key request header (see the explanation of how API keys are read).

From here on, I store the API ID in $API, and the IDs of the root (/), /items, and /health resources in $ROOT, $ITEMS, and $HEALTH. I retrieved $API and $ROOT as follows. I retrieved $ITEMS and $HEALTH the same way after creating the resources, changing only the 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)

I created the resources with 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

To require a key, use --api-key-required with put-method (see how to require a key on a method). For /health, where I left the flag off, apiKeyRequired came back as 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
}

I added MOCK integrations and method responses to both methods. /items returns {"items": ["tama", "mike"]}, and /health returns {"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\"}"
}

A REST API cannot be called until you deploy it and create a stage (see the explanation of how to call a REST API). I deployed it to a stage named dev.

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

Calling without a key returns 403 only for the keyed method

In the emulator, the URL for stage dev was https://127.0.0.1:9297/_aws/execute-api/<API ID>/dev. I stored this URL in $U (U="https://127.0.0.1:9297/_aws/execute-api/$API/dev") and called it with curl. --cacert tells curl to trust the certificate that the emulator generated. On real AWS, the URL takes the form https://<API ID>.execute-api.<region>.amazonaws.com/<stage>/, as described in the official documentation.

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"}

The curl commands shown in this article omit the ; echo I added at the end to put a newline after the output.

Creating a key alone still returns 403

I created a key with create-api-key. The emulator generated the value.

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": {}
}

A key has two identifiers: an id for management, and a value that you give to the consumer. In the get-api-keys list, value is null. To see the value, I used get-api-key with --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"
}

I stored the key's id in $KA and its value in $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)

Calling with the value in the x-api-key header still returned 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"}

The explanation of API key setup also says that after you create a key, you must add it to a usage plan. API Gateway checks the key it receives against the keys in the usage plans, and returns 403 if it finds no match (see the explanation of how API keys are read).

Add the key to a plan limited to 3 calls per day and exceed the limit

With create-usage-plan, I created a plan that targets stage dev and has only a quota (--quota): up to 3 calls per day (DAY).

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": {}
}

I stored the plan's ID in $PQ, then added key A to the plan with create-usage-plan-key.

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"
}

When I called with the same key, I got 200. In the emulator, the call succeeded right after I added the key to the plan. On real API Gateway, the official documentation says that updates that add a key to a plan can take a few minutes to complete.

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"]}

When I sent a value that matched no key, I got 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"}

Next, I made four more calls, each 1.5 seconds apart. Counting the first call, the first three returned 200, and the fourth and later returned 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"}

After I hit the limit, /health, which does not require a key, still returned 200 even with the same key attached.

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

Check usage and remaining calls with get-usage

get-usage shows the daily usage for each key. Each entry in the inner array is [calls used, calls remaining] (see the get-usage reference). The fourth and fifth calls were rejected and were not counted. The one call I sent with -si to inspect the output was also not counted. The result was [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"
}

Change the remaining calls with update-usage

update-usage temporarily changes the remaining calls for the current period, for that key only. When I set the remaining count to 2, the first two calls returned 200, and the third returned 429 again.

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

The per-second limit returns 429 only when requests are sent back to back

The per-second limit follows the token bucket model described in the explanation of request throttling. rateLimit is the number of tokens (one per request) added per second, and burstLimit is the size of the bucket.

To keep this separate from the daily quota, I created a second key, example-key-b. I stored its id in $KB and its value in $VB, following the same steps as key A. Then I added it to a different plan that had only rateLimit 1 and burstLimit 2. I stored that plan's ID in $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"
}

When I sent six requests in a row without waiting, the first two (the burstLimit) returned 200, and the third and later returned 429. The time at the start of each line is the send time (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

The 429 response here has a different body and x-amzn-errortype than the daily quota one. It returned Too Many Requests and 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"}

After waiting 3 seconds, I sent six requests 1.1 seconds apart. All of them returned 200. Because the interval is slightly longer than one second per request, the tokens never ran out.

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 for this plan showed [13, 0]. The 13 is the total number of calls key B had sent up to this point: eight that returned 200 and five that returned 429. Calls rejected by the quota were not counted, but calls rejected by the per-second limit were. This plan has no quota, but the remaining count still shows 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"
}

Disabling a key returns 403 even when it is in a plan

When I set enabled to false with update-api-key, key B returned 403. When I set it back to true, calls returned 200 again.

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

Here is a single image summarizing the results so far.

Responses to GET /items. Without the x-api-key header, with a key that is not in any usage plan, with a non-existent key value, or with a disabled key, the response is 403 Forbidden. A key in a usage plan returns 200 OK. Exceeding the daily quota returns 429 Limit Exceeded, and exceeding the per-second limit returns 429 Too Many Requests.
The status the emulator returned for each key state and limit, and the message in the body for error responses.

In the list of API Gateway gateway response types, the defaults are 403 for an invalid key (INVALID_API_KEY), and 429 for exceeding the quota (QUOTA_EXCEEDED) or the per-second limit (THROTTLED). The statuses the emulator returned matched this table.

Warning

The best practices for usage plans and API keys say not to use API keys for authentication or authorization (controlling who can use an API). If one plan contains several APIs, a key for one API can call every API in that plan. The documentation recommends IAM roles, Lambda authorizers, and Amazon Cognito user pools for access control. The explanation of usage plans and API keys on the same page also says that throttling and quotas are not hard limits, so consumers may exceed them. Do not rely on them to control costs or to block access.

Remove the stage before deleting a usage plan

When I cleaned up and ran delete-usage-plan, I got an error saying the plan could not be deleted because an API stage was still attached to it.

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

After I removed dev from /apiStages with update-usage-plan, I could delete the plans. Then I deleted the keys and the 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": []
}

As described in the AWS Emulator limits documentation, the emulator keeps the resources you create in memory and discards them when it stops. API keys, usage plans, and usage counts are also gone once the emulator stops.

​Posted by 86