English

AWS EmulatorでAPI GatewayからLambdaを呼ぶ方法

​​AWS Emulator​Amazon API Gateway,AWS CLI,AWS Lambda,Python,テスト

AWS Emulator に API Gateway の HTTP API を作り、Lambda 関数をつなぐと、curl で送った HTTP リクエストが関数に届き、関数の戻り値が HTTP の応答として返ってくるところまで、手元で動かせます。AWS のアカウントは要りません。サーバーレスの Web API やバックエンドを、デプロイする前にローカル環境や CI で試したいときに使えます。

補足

検証環境は Ubuntu 24.04.5(x86_64)、AWS Emulator 1.0.533(2026年11月19日リリース、Debian パッケージ)、AWS CLI 2.41.2、curl 8.5.0 です。AWS のアカウントと認証情報は使っていません。本物の API Gateway と Lambda での動き、料金、応答にかかる時間は確かめておらず、記事で触れるところは公式ドキュメントを出どころにしています。REST API(aws apigateway のほう)、名前付きのステージ、オーソライザー、CORS の設定、カスタムドメインは試していません。

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

AWS Emulator は、公式ガイドにある Linux での入れ方のとおりに、Debian パッケージの署名を gpg で確かめてから入れました。

1つ目の端末で起動します。-t off は、使用状況のデータ(テレメトリー)を送らない指定です。

bash
aws-emulator -t off

2つ目の端末で、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=""

HTTP API は API Gateway のバージョン2の API で作るものなので、AWS CLI では aws apigatewayv2 を使います(HTTP API と REST API の違いの説明)。起動した直後は、API も関数も1つもありません。

text
$ aws apigatewayv2 get-apis
{
    "Items": []
}
$ aws lambda list-functions --query "Functions[].FunctionName"
[]

HTTP の応答を返す Lambda 関数を作る

まず、クエリ文字列の name を読んで、あいさつを JSON で返す関数を Python で書きました。

python
# fn/hello.py
import json

def lambda_handler(event, context):
    name = (event.get("queryStringParameters") or {}).get("name", "world")
    return {
        "statusCode": 200,
        "headers": {"content-type": "application/json"},
        "body": json.dumps({"message": f"hello, {name}"}),
    }

戻り値の statusCode、headers、body が、そのまま HTTP の応答のステータス、ヘッダー、本文になります。body には文字列を入れます(HTTP API から呼ばれる関数が返す形の説明)。

関数の実行ロール example-lambda-role を、lambda.amazonaws.com が引き受けられる信頼ポリシーで作り、関数を lambda_function.py という名前で zip にまとめてから、create-function で登録しました。あとで使う2つの関数 example-echo と example-boom も、同じ手順で一緒に作っています。zip には次のコマンドでまとめました。

text
$ for f in hello echo boom; do (cd fn && rm -f ../$f.zip && cp $f.py lambda_function.py && zip -q ../$f.zip lambda_function.py && rm lambda_function.py); done; ls *.zip
boom.zip
echo.zip
hello.zip

できた zip を、create-function で登録します。

text
$ ACC=$(aws sts get-caller-identity --query Account --output text); for f in hello echo boom; do aws lambda create-function --function-name example-$f --runtime python3.12 --handler lambda_function.lambda_handler --role arn:aws:iam::$ACC:role/example-lambda-role --zip-file fileb://$f.zip --query "[FunctionName,State]" --output text; done
example-hello	Pending
example-echo	Pending
example-boom	Pending
$ for f in hello echo boom; do aws lambda wait function-active-v2 --function-name example-$f; aws lambda get-function-configuration --function-name example-$f --query "[FunctionName,State]" --output text; done
example-hello	Active
example-echo	Active
example-boom	Active

作った直後は Pending なので、wait function-active-v2 で Active になるのを待ってから先に進みます。Lambda 関数の作り方そのものは、「AWS EmulatorでLambda関数を作って呼び出す方法」の記事に詳しく書きました。

クイック作成で、関数につながる API を1回で作る

create-api に --target で関数の ARN を渡すと、API、Lambda 関数とのインテグレーション(API と関数を結ぶ設定)、すべてのリクエストを受けるルート、自動でデプロイされるステージを、まとめて作れます。HTTP API のクイック作成の説明にある書き方です。

text
$ aws apigatewayv2 create-api --name example-hello-api --protocol-type HTTP --target arn:aws:lambda:us-east-1:$(aws sts get-caller-identity --query Account --output text):function:example-hello
{
    "ApiEndpoint": "https://127.0.0.1:9297/_aws/execute-api/mp67t4dbd4",
    "ApiId": "mp67t4dbd4",
    "ApiKeySelectionExpression": "$request.header.x-api-key",
    "CreatedDate": "2026-11-20T02:53:32.357122+00:00",
    "DisableSchemaValidation": false,
    "DisableExecuteApiEndpoint": false,
    "IpAddressType": "ipv4",
    "Name": "example-hello-api",
    "ProtocolType": "HTTP",
    "RouteSelectionExpression": "$request.method $request.path",
    "Tags": {}
}

呼び出すときの URL は ApiEndpoint に入っています。エミュレーターでは、https://127.0.0.1:9297/_aws/execute-api/<API の ID> の形でした。本物の AWS では、公式ドキュメントの例のとおり https://<API の ID>.execute-api.<リージョン>.amazonaws.com の形になります。

作られたものを見ると、ルートは $default が1つ、インテグレーションは AWS_PROXY でペイロードの形式が 2.0、ステージは $default で AutoDeploy が true でした。

text
$ aws apigatewayv2 get-routes --api-id mp67t4dbd4 --query 'Items[].[RouteKey,Target]' --output text
$default	integrations/ur7ayid
$ aws apigatewayv2 get-integrations --api-id mp67t4dbd4 --query 'Items[].{Type:IntegrationType,Uri:IntegrationUri,Payload:PayloadFormatVersion}'
[
    {
        "Type": "AWS_PROXY",
        "Uri": "arn:aws:lambda:us-east-1:<12桁のアカウントID>:function:example-hello",
        "Payload": "2.0"
    }
]
$ aws apigatewayv2 get-stages --api-id mp67t4dbd4 --query 'Items[].{Stage:StageName,AutoDeploy:AutoDeploy,Message:LastDeploymentStatusMessage}'
[
    {
        "Stage": "$default",
        "AutoDeploy": true,
        "Message": "Successfully deployed stage with deployment id 'wjslhw'"
    }
]

出力の中のアカウントIDは、<12桁のアカウントID> に置き換えています。

呼び出しの許可がないと、500 が返る

この状態で curl から呼ぶと、エミュレーターは 500 を返しました。

text
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem 'https://127.0.0.1:9297/_aws/execute-api/mp67t4dbd4/hello?name=neko'
HTTP/1.1 500 Internal Server Error
content-type: application/json
content-length: 35
x-amzn-requestid: 18e9a13e298a622c
date: Fri, 20 Nov 2026 02:53:34 GMT

{"message":"Internal Server Error"}

--cacert は、エミュレーターが起動のたびに作る証明書を curl に信頼させる指定です。リクエストに AWS の署名は付けていません。記事に載せた curl のコマンドでは、出力の最後に改行を足すために付けた ; echo を省いています。

応答だけでは理由が分かりませんが、エミュレーターのログ(1つ目の端末に1行ずつ出る JSON)に、関数が API Gateway からの呼び出しを許していないので呼ばなかった、という行が出ていました。その行の fields の部分を取り出して整形すると、次のとおりです。

text
{
  "message": "refusing an invoke: this route's function allows the gateway no invocation for it, so none was made",
  "api_id": "mp67t4dbd4",
  "stage": "$default",
  "route_key": "$default",
  "function": "arn:aws:lambda:us-east-1:<12桁のアカウントID>:function:example-hello"
}

コマンドのリファレンスにあるログの説明によると、起動の行以外のログの中身は、リリースごとに変わることがあります。

Lambda の、API Gateway から呼ぶときの権限の説明にあるとおり、API Gateway から関数を呼べるようにするには、関数のリソースベースのポリシーで許可を与えます(クイック作成の説明によると、IAM ロールで許可する方法もあります)。コンソールで API を関数に追加すると自動で付きますが、AWS CLI で作ったときは、自分で add-permission を実行します。--source-arn の mp67t4dbd4/* は、この API のすべてのステージ、メソッド、パスからの呼び出しを許す指定です。

text
$ aws lambda add-permission --function-name example-hello --statement-id apigw-invoke --action lambda:InvokeFunction --principal apigateway.amazonaws.com --source-arn "arn:aws:execute-api:us-east-1:$(aws sts get-caller-identity --query Account --output text):mp67t4dbd4/*"
{
    "Statement": "{\"Sid\":\"apigw-invoke\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"apigateway.amazonaws.com\"},\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:us-east-1:<12桁のアカウントID>:function:example-hello\",\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:execute-api:us-east-1:<12桁のアカウントID>:mp67t4dbd4/*\"}}}"
}

もう一度呼ぶと、関数が返した statusCode、content-type、body のとおりの応答が返りました。

text
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem 'https://127.0.0.1:9297/_aws/execute-api/mp67t4dbd4/hello?name=neko'
HTTP/1.1 200 OK
content-type: application/json
content-length: 26
x-amzn-requestid: 86ded88713608136
date: Fri, 20 Nov 2026 02:53:36 GMT

{"message": "hello, neko"}

ルートが $default だけなので、パスやメソッドを変えても、同じ関数に届きます。

text
$ curl -s --cacert ~/.aws/emulator/9297/ca.pem https://127.0.0.1:9297/_aws/execute-api/mp67t4dbd4/
{"message": "hello, world"}
$ curl -s -X DELETE --cacert ~/.aws/emulator/9297/ca.pem https://127.0.0.1:9297/_aws/execute-api/mp67t4dbd4/any/path
{"message": "hello, world"}
注意

AWS Emulator の制限の説明には、IAM のポリシーとリソースベースのポリシーを AWS と同じようには評価しないので、セキュリティのテストに使わないように、と書かれています。この検証では許可がないと呼ばれませんでしたが、エミュレーターで通った許可が本物の AWS でも足りるかどうかは、この結果からは分かりません。

ルートを自分で決めて、メソッドとパスで関数を呼び分ける

クイック作成の $default ルートは、どのリクエストも同じ関数に送ります。GET /items/{id} のように、メソッドとパスごとに受けるには、API、インテグレーション、ルート、ステージを1つずつ作ります。HTTP API を作る説明にあるとおり、動く API にはルート、インテグレーション、ステージ、デプロイがそれぞれ1つ以上要ります。

ここでつなぐ関数 example-echo は、statusCode を付けずに、受け取った event の一部をそのまま返します。

python
# fn/echo.py
def lambda_handler(event, context):
    # statusCode を付けずに、受け取った event の一部をそのまま返す
    return {
        "routeKey": event["routeKey"],
        "method": event["requestContext"]["http"]["method"],
        "rawPath": event["rawPath"],
        "pathParameters": event.get("pathParameters"),
        "queryStringParameters": event.get("queryStringParameters"),
        "body": event.get("body"),
        "isBase64Encoded": event["isBase64Encoded"],
        "version": event["version"],
    }

もう1つの関数 example-boom は、呼ばれると例外を出すだけです。

python
# fn/boom.py
def lambda_handler(event, context):
    raise RuntimeError("something went wrong")

--target を付けずに API を作り、関数ごとにインテグレーションを作ります。AWS CLI でインテグレーションを作るときは、--payload-format-version が必須です(ペイロードの形式の説明)。

text
$ aws apigatewayv2 create-api --name example-items-api --protocol-type HTTP --query "{ApiId:ApiId,ApiEndpoint:ApiEndpoint}"
{
    "ApiId": "e77k44w5b0",
    "ApiEndpoint": "https://127.0.0.1:9297/_aws/execute-api/e77k44w5b0"
}
$ aws apigatewayv2 create-integration --api-id e77k44w5b0 --integration-type AWS_PROXY --integration-uri arn:aws:lambda:us-east-1:$(aws sts get-caller-identity --query Account --output text):function:example-echo --payload-format-version 2.0 --query '{IntegrationId:IntegrationId,Type:IntegrationType,Payload:PayloadFormatVersion}'
{
    "IntegrationId": "390335c",
    "Type": "AWS_PROXY",
    "Payload": "2.0"
}
$ aws apigatewayv2 create-integration --api-id e77k44w5b0 --integration-type AWS_PROXY --integration-uri arn:aws:lambda:us-east-1:$(aws sts get-caller-identity --query Account --output text):function:example-boom --payload-format-version 2.0 --query IntegrationId --output text
ju0my48

ルートのキーは、メソッドとパスを半角スペースで区切って書き(例:GET /items/{id})、--target に integrations/<インテグレーションの ID> を渡します。パスの {id} は、その部分の値を関数に渡すパス変数です(ルートの説明)。

text
$ aws apigatewayv2 create-route --api-id e77k44w5b0 --route-key 'GET /items/{id}' --target integrations/390335c --query '[RouteKey,Target]' --output text
GET /items/{id}	integrations/390335c
$ aws apigatewayv2 create-route --api-id e77k44w5b0 --route-key 'POST /items' --target integrations/390335c --query '[RouteKey,Target]' --output text
POST /items	integrations/390335c
$ aws apigatewayv2 create-route --api-id e77k44w5b0 --route-key 'GET /boom' --target integrations/ju0my48 --query '[RouteKey,Target]' --output text
GET /boom	integrations/ju0my48

2つの関数にも、前の節と同じ形の add-permission で、この API からの呼び出しを許可しました。

ステージを作るまでは 404 になる

ルートまで作ったところで呼ぶと、{"message":"Not Found"} の 404 が返りました。

text
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem https://127.0.0.1:9297/_aws/execute-api/e77k44w5b0/items/42
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 23
x-amzn-requestid: 603447a5b6b6964a
date: Fri, 20 Nov 2026 02:53:44 GMT

{"message":"Not Found"}

リクエストの振り分け方の説明にも、$default ステージがないと {"message":"Not Found"} を返す、と書かれています。$default ステージを、--auto-deploy を付けて作ります。

text
$ aws apigatewayv2 create-stage --api-id e77k44w5b0 --stage-name '$default' --auto-deploy --query '{Stage:StageName,AutoDeploy:AutoDeploy,Message:LastDeploymentStatusMessage}'
{
    "Stage": "$default",
    "AutoDeploy": true,
    "Message": "Successfully deployed stage with deployment id '51lenj'"
}

$default ステージは、URL のパスにステージの名前を入れずに呼べます。名前を付けたステージでは、パスの先頭にステージの名前が入ります(Lambda の、HTTP API の機能の説明)。

ルートに当たったリクエストだけが関数に届く

ステージを作ってから、5つのリクエストを送りました。結果をまとめると、次の図のとおりです。

GET /items/42?color=white は GET /items/{id} に当たって 200、POST /items は POST /items に当たって 200、GET /items と DELETE /items/42 は当たるルートがなく 404、GET /boom は GET /boom に当たるが関数が例外を出して 500 になった
5つのリクエストが当たったルートと、返ってきた応答のステータス

GET /items/42?color=white は GET /items/{id} に当たり、example-echo が受け取った event の中身が返ってきました。パスの 42 は pathParameters の id に、クエリ文字列は queryStringParameters に入っています。

text
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem 'https://127.0.0.1:9297/_aws/execute-api/e77k44w5b0/items/42?color=white'
HTTP/1.1 200 OK
content-type: application/json
content-length: 190
x-amzn-requestid: 0ffcc1df0c357f9a
date: Fri, 20 Nov 2026 02:53:44 GMT

{"routeKey":"GET /items/{id}","method":"GET","rawPath":"/items/42","pathParameters":{"id":"42"},"queryStringParameters":{"color":"white"},"body":null,"isBase64Encoded":false,"version":"2.0"}

example-echo は statusCode も headers も返していませんが、応答は 200 で、content-type は application/json でした。形式 2.0 の応答の説明にある、関数が statusCode のない JSON を返したときは、ステータスを 200、content-type を application/json とみなし、戻り値を本文にする、という動きと同じです。

POST /items で JSON を送ると、body には JSON がオブジェクトではなく文字列のまま入っていました。関数の中で使うときは、json.loads(event["body"]) のように読み込みます。

text
$ curl -s --cacert ~/.aws/emulator/9297/ca.pem -X POST -H 'content-type: application/json' -d '{"name":"tama"}' https://127.0.0.1:9297/_aws/execute-api/e77k44w5b0/items | python3 -m json.tool
{
    "routeKey": "POST /items",
    "method": "POST",
    "rawPath": "/items",
    "pathParameters": null,
    "queryStringParameters": null,
    "body": "{\"name\":\"tama\"}",
    "isBase64Encoded": false,
    "version": "2.0"
}

GET /items(/items の GET のルートはない)と DELETE /items/42(/items/{id} には GET しかない)は、どちらも 404 になりました。この API には $default ルートを作っていないので、当たらなかったリクエストを受けるところがありません。ルートの説明にある、どのルートにも当たらないときは {"message":"Not Found"} を返す、という動きです。

text
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem https://127.0.0.1:9297/_aws/execute-api/e77k44w5b0/items
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 23
x-amzn-requestid: 4b6df552019da683
date: Fri, 20 Nov 2026 02:53:44 GMT

{"message":"Not Found"}
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem -X DELETE https://127.0.0.1:9297/_aws/execute-api/e77k44w5b0/items/42
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 23
x-amzn-requestid: e9526c8b8791e75c
date: Fri, 20 Nov 2026 02:53:44 GMT

{"message":"Not Found"}

GET /boom はルートに当たりますが、関数が例外を出すので、500 と {"message":"Internal Server Error"} が返りました。例外のメッセージ something went wrong は、応答には入っていません。呼び出しの許可がないときの 500 と、本文は同じでした。

text
$ curl -si --cacert ~/.aws/emulator/9297/ca.pem https://127.0.0.1:9297/_aws/execute-api/e77k44w5b0/boom
HTTP/1.1 500 Internal Server Error
content-type: application/json
content-length: 35
x-amzn-requestid: 971ae6c507ee7b8d
date: Fri, 20 Nov 2026 02:53:44 GMT

{"message":"Internal Server Error"}
ポイント

HTTP API で関数を呼ぶには、ルート、インテグレーション、ステージ(この記事では $default)、関数の add-permission の4つをそろえます。エミュレーターでは、ステージがないときやルートに当たらないときは 404、許可がないときや関数が失敗したときは 500 が返ったので、応答のステータスから、どこが足りないかの見当をつけられます。

API と関数を消して、エミュレーターを止める

作った2つの API を delete-api で、3つの関数を delete-function で消しました。

text
$ for a in $(aws apigatewayv2 get-apis --query 'Items[].ApiId' --output text); do aws apigatewayv2 delete-api --api-id $a; done; aws apigatewayv2 get-apis
{
    "Items": []
}
$ for f in hello echo boom; do aws lambda delete-function --function-name example-$f; done; aws lambda list-functions --query "Functions[].FunctionName"
{
    "StatusCode": 204
}
{
    "StatusCode": 204
}
{
    "StatusCode": 204
}
[]

AWS Emulator の制限の説明にあるとおり、エミュレーターは作ったリソースをメモリーに置き、止めると消します。検証環境では、エミュレーターのプロセスに SIGTERM を送ると、終了コード 0 で止まりました。

​Posted by 86