日本語

How to Call Lambda from API Gateway in AWS Emulator

​​AWS Emulator​Amazon API Gateway,AWS CLI,AWS Lambda,Python,Testing

With AWS Emulator, you can create an HTTP API in API Gateway, connect it to a Lambda function, and run the whole path locally: an HTTP request sent with curl reaches the function, and the function's return value comes back as the HTTP response. You don't need an AWS account. This is useful for testing a serverless web API or backend in a local environment or CI before you deploy it.

Note

Test environment: Ubuntu 24.04.5 (x86_64), AWS Emulator 1.0.533 (released November 19, 2026, Debian package), AWS CLI 2.41.2, curl 8.5.0. I did not use an AWS account or credentials. I have not checked how this behaves on real API Gateway and Lambda, the pricing, or the response times. Where the article mentions these, it relies on the official documentation. I did not test REST APIs (the aws apigateway side), named stages, authorizers, CORS settings, or custom domains.

Start the emulator and point the AWS CLI at it

I installed AWS Emulator on Linux as described in the official guide, and verified the Debian package signature with gpg first.

Start it in the first terminal. -t off turns off sending usage data (telemetry).

bash
aws-emulator -t off

In a second terminal, set the environment variables from the guide on pointing an SDK at the emulator. I added the last line, AWS_PAGER, so the 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=""

An HTTP API is a version 2 API in API Gateway, so you create it with aws apigatewayv2 in the AWS CLI (see the explanation of HTTP APIs and REST APIs). Right after startup, there are no APIs or functions.

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

Create a Lambda function that returns an HTTP response

First, I wrote a Python function that reads the name query string parameter and returns a greeting as JSON.

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

The returned statusCode, headers, and body become the HTTP status, headers, and body of the response. body must be a string (see how a function called from an HTTP API returns its result).

I created the function's execution role example-lambda-role with a trust policy that lets lambda.amazonaws.com assume it. I then packaged the function as lambda_function.py in a zip file and registered it with create-function. The two functions I use later, example-echo and example-boom, were created the same way. I packaged the zip files with this command:

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

I registered the zip files with 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

Right after creation the state is Pending, so I used wait function-active-v2 to wait until it becomes Active before continuing. I covered how to create Lambda functions in more detail in my article on creating and invoking a Lambda function in AWS Emulator.

Create an API connected to a function in one step with quick create

If you pass the function's ARN with --target to create-api, it creates the API, the integration (the setting that connects the API to the function), a route that receives all requests, and a stage that is deployed automatically, all at once. This is the approach in the explanation of HTTP API quick create.

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

The URL for calling the API is in ApiEndpoint. In the emulator, it had the form https://127.0.0.1:9297/_aws/execute-api/<API ID>. On real AWS, the form is https://<API ID>.execute-api.<region>.amazonaws.com, as in the official documentation example.

Looking at what was created: there was one route, $default. The integration was AWS_PROXY with payload format 2.0. The stage was $default with AutoDeploy set to 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'"
    }
]

In the output, I replaced the account ID with a placeholder.

Without invoke permission, you get a 500

When I called the API with curl in this state, the emulator returned a 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 tells curl to trust the certificate that the emulator generates each time it starts. I did not add any AWS signature to the request. In the curl commands shown in this article, I left out the ; echo I used to add a newline at the end of the output.

The response alone doesn't explain the cause. However, the emulator log (one JSON line per event, printed in the first terminal) had a line saying that the function does not allow invocation from API Gateway, so it did not call it. Pulling out the fields part of that line and formatting it gives:

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

According to the log explanation in the CLI reference, the contents of log lines other than the startup line may change between releases.

As described in the Lambda explanation of permissions for invoking from API Gateway, you grant API Gateway permission to invoke the function with a resource-based policy on the function. (The quick create explanation also mentions a way to grant this through an IAM role.) The console adds this permission automatically when you attach an API to a function. When you create the API with the AWS CLI, you run add-permission yourself. The mp67t4dbd4/* in --source-arn allows invocations from all stages, methods, and paths of this 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/*\"}}}"
}

When I called the API again, the response matched the statusCode, content-type, and body the function returned.

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

Because the only route is $default, changing the path or method still reaches the same function.

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

The AWS Emulator limitations explanation says that IAM policies and resource-based policies are not evaluated the same way as on AWS, so the emulator should not be used for security testing. In this test, the function was not invoked without the permission, but this result does not show whether a permission that passes in the emulator is also sufficient on real AWS.

Choose the routes yourself, and dispatch to functions by method and path

The $default route from quick create sends every request to the same function. To handle requests by method and path, such as GET /items/{id}, you create the API, integrations, routes, and stage one at a time. As the HTTP API creation guide explains, a working API needs at least one route, one integration, one stage, and one deployment.

The function example-echo, which I connect here, does not return a statusCode. It returns part of the received event as-is.

python
# fn/echo.py
def lambda_handler(event, context):
    # Return part of the received event as-is, without statusCode
    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"],
    }

The other function, example-boom, just raises an exception when invoked.

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

I created an API without --target, then created an integration for each function. When you create an integration with the AWS CLI, --payload-format-version is required (see the payload format explanation).

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

For a route key, write the method and path separated by a single space (for example, GET /items/{id}), and pass integrations/<integration ID> to --target. The {id} in the path is a path variable that passes the value in that position to the function (see the route explanation).

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

I also granted both functions permission to be invoked from this API, using the same add-permission form as in the previous section.

Requests return 404 until the stage is created

When I called the API right after creating the routes, I got a 404 with {"message":"Not Found"}.

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

The explanation of how requests are routed also says that without a $default stage, the API returns {"message":"Not Found"}. I created the $default stage with --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'"
}

With the $default stage, you call the API without including the stage name in the URL path. With a named stage, the stage name becomes the first segment of the path (see the explanation of HTTP API features in Lambda).

Only requests that match a route reach the function

After creating the stage, I sent five requests. The diagram below summarizes the results.

GET /items/42?color=white matches GET /items/{id} and returns 200. POST /items matches POST /items and returns 200. GET /items and DELETE /items/42 match no route and return 404. GET /boom matches GET /boom, but the function raises an exception and the response is 500.
The routes the five requests matched, and the status of each response

GET /items/42?color=white matched GET /items/{id}, and the response contained the event that example-echo received. The 42 in the path is in pathParameters as id, and the query string is in 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 returns neither statusCode nor headers, but the response was 200 and content-type was application/json. This matches the behavior in the version 2.0 response explanation: when a function returns JSON without statusCode, the status is treated as 200, content-type as application/json, and the return value becomes the body.

When I sent JSON with POST /items, body contained the JSON as a string, not as an object. In your function, read it with something like 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 (there is no GET route for /items) and DELETE /items/42 (/items/{id} only has GET) both returned 404. I did not create a $default route for this API, so there is nothing to receive requests that don't match. This matches the route explanation: when no route matches, the API returns {"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 matched its route, but the function raised an exception, so the response was 500 with {"message":"Internal Server Error"}. The exception message something went wrong does not appear in the response. The body was the same as the 500 I got when invoke permission was missing.

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

To call a function through an HTTP API, you need four things: a route, an integration, a stage ($default in this article), and add-permission on the function. In the emulator, a missing stage or a request that matches no route returned 404, and a missing permission or a failing function returned 500. The response status gives you a good idea of what is missing.

Delete the API and functions, then stop the emulator

I deleted the two APIs with delete-api and the three functions with 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
}
[]

As described in the AWS Emulator limitations explanation, the emulator keeps the resources you create in memory and discards them when it stops. In my test environment, sending SIGTERM to the emulator process stopped it with exit code 0.

​Posted by 86