Sub topic 13
Testing locally and debugging failures
This chapter assumes you have read the earlier chapters on the version 2.0 payload, route keys, and the SAM template. It also assumes you can run Python 3.13, pytest, the AWS CLI, the SAM CLI and Docker. You will test the ItemsFunction handler at three levels: plain unit tests, SAM's local emulation, and the deployed API. Then you will learn to trace a failing request to its cause.
Choosing a test level
Each level catches a different class of bug, and each costs a different amount of time.
| Level | Tool | Catches | Misses |
|---|---|---|---|
| Unit test | pytest calling `handler` directly | Logic errors, bad status codes, JSON mistakes | Routing, packaging, permissions |
| Local emulation | `sam local invoke`, `sam local start-api` | Packaging, runtime, import errors, event shape | Authorizers, throttling, real IAM |
| Deployed API | `curl`, `aws lambda invoke` | Everything, including permissions and CORS | Nothing, but it is the slowest loop |
Start at the top of the table and work down. Most bugs show up in unit tests, which run in milliseconds.
Sample events
A Lambda handler is a function that takes a dictionary. To test it, you build a dictionary that looks like what API Gateway sends. Save this as events/get-item.json:
{
"version": "2.0",
"routeKey": "GET /items/{id}",
"rawPath": "/items/42",
"rawQueryString": "",
"headers": {
"content-type": "application/json"
},
"requestContext": {
"routeKey": "GET /items/{id}",
"http": {
"method": "GET",
"path": "/items/42"
}
},
"pathParameters": {
"id": "42"
},
"isBase64Encoded": false
}Notice that routeKey holds the route template, while rawPath holds the actual path the client called. The handler from the earlier chapter branches on the route key and reads pathParameters, so both must be present and consistent. A hand-written event with a mismatched route key is a common reason a test passes locally but the real API returns something else.
You can also capture real events. Log json.dumps(event) from a deployed function once, then copy the output from CloudWatch Logs into a file. Remove tokens and other secrets before you commit it.
sam local generate-event apigateway http-api-proxy prints a version 2.0 sample event you can edit.
Unit testing the handler
The handler needs no AWS services, so you can import and call it. Save this as tests/test_app.py, next to a src/app.py that holds the handler from the earlier chapter:
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
from app import handler # noqa: E402
def make_event(route_key, raw_path, path_parameters=None, body=None):
method = route_key.split(" ", 1)[0]
return {
"version": "2.0",
"routeKey": route_key,
"rawPath": raw_path,
"headers": {"content-type": "application/json"},
"requestContext": {
"routeKey": route_key,
"http": {"method": method, "path": raw_path},
},
"pathParameters": path_parameters,
"body": body,
"isBase64Encoded": False,
}
def test_get_item_returns_id():
event = make_event("GET /items/{id}", "/items/42", {"id": "42"})
response = handler(event, None)
assert response["statusCode"] == 200
assert json.loads(response["body"]) == {"id": "42"}
def test_response_body_is_a_string():
event = make_event("GET /items/{id}", "/items/42", {"id": "42"})
assert isinstance(handler(event, None)["body"], str)
def test_post_valid_json_returns_201():
event = make_event("POST /items", "/items", body='{"name": "widget"}')
response = handler(event, None)
assert response["statusCode"] == 201
def test_post_invalid_json_returns_400():
event = make_event("POST /items", "/items", body="{not json")
assert handler(event, None)["statusCode"] == 400
def test_post_missing_body_returns_400():
event = make_event("POST /items", "/items", body=None)
assert handler(event, None)["statusCode"] == 400
def test_unknown_route_returns_404():
event = make_event("DELETE /items/{id}", "/items/1", {"id": "1"})
assert handler(event, None)["statusCode"] == 404Run it with python -m pytest tests -q. Passing None as the context works here because the handler never reads it. If you later use context.aws_request_id, pass a small stand-in object, such as types.SimpleNamespace(aws_request_id="test").
The test_response_body_is_a_string test guards against a frequent mistake. API Gateway expects body to be a string, so returning a dictionary there is a bug that only shows up after deployment.
Running locally with SAM
SAM runs your function inside a Docker container that mimics the Lambda runtime. Run these from the folder that holds template.yaml:
sam build
sam local invoke ItemsFunction --event events/get-item.json
sam local start-api --port 3000
curl -i http://127.0.0.1:3000/items/42sam local invoke runs the function once with your event file and prints the response and the log lines. sam local start-api starts a local web server that translates HTTP requests into version 2.0 events based on the Events section of your template. Run sam build after every code change, because the local commands use the built copy in .aws-sam/build.
Local emulation does not reproduce everything the cloud does. Authorizers, throttling, IAM checks and the full CORS behavior of the API run only in API Gateway. Treat a local success as proof that the code and packaging work, not that the API is correctly configured.
Calling the deployed function and API
To isolate the function from the API, invoke the function directly with the same event file:
aws lambda invoke \
--function-name ItemsFunction-REPLACE_WITH_REAL_NAME \
--payload fileb://events/get-item.json \
response.json
cat response.jsonSAM adds a generated suffix to the physical function name. Find it with aws cloudformation describe-stack-resources --stack-name items-api. If the direct invoke works but the URL fails, the problem lies in the route, the integration or the authorizer. If both fail, the problem is in the function.
Reading failures by status code
Start from the status code the client saw. It tells you which component produced the error.
The table below lists the causes that come up most often.
| Symptom | Likely cause | Where to confirm |
|---|---|---|
| 404 `{"message":"Not Found"}` | Method or path has no route and there is no `$default` route | The `Events` section of the template |
| 500 `{"message":"Internal Server Error"}` with a traceback in the logs | Unhandled exception, such as a `KeyError` on a missing path parameter or a missing `pathParameters` dictionary | Function log group |
| 500 with no function logs | API Gateway has no permission to invoke the function, or the integration points at the wrong function | Lambda resource policy and the integration target |
| 500 with a clean function log | Invalid response shape, such as a non-string `body` or a non-dictionary return value that is not JSON-serializable | Access log field `$context.integrationErrorMessage` |
| 500 after about the function timeout | The function hit its `Timeout` (10 seconds in the template) | A `Task timed out` line in the function logs |
| 504 | The integration exceeded the HTTP API's integration timeout (30 seconds by default and at most) | Function duration in the logs |
| 401 or 403 | JWT validation failed, the Lambda authorizer returned `isAuthorized: false`, or the IAM caller lacks permission | Authorizer configuration and the request headers |
REST APIs return 502 for malformed proxy responses. HTTP APIs return 500 for the same problem, so do not search for a 502 on an HTTP API.
Making failures easier to find
Three habits make debugging faster.
- Return a clear 4xx for bad input, as the handler already does for malformed JSON. A 400 you chose is easier to diagnose than a 500 from an exception.
- Log the request ID.
event["requestContext"]["requestId"]matches the$context.requestIdfield in your access logs, so you can jump from an API Gateway log line to the function's log lines for the same request. - Log failures with context before you return them, for example
print(json.dumps({"requestId": rid, "route": route, "error": str(exc)})). Lambda sends anything written to standard output to CloudWatch Logs.
To follow the logs of a deployed function while you reproduce the problem, run:
sam logs --stack-name items-api --name ItemsFunction --tailUse $context.integrationErrorMessage, $context.integration.status and $context.error.message in the access log format. They separate "the function failed" from "API Gateway rejected the request before the function ran."
Exercise
A client reports that POST /items returns 500 Internal Server Error. Your unit tests pass, and the function's log group has no entries for the request. Name two likely causes and the first place you would look for each.
Show answer
The most likely cause is that API Gateway could not invoke the function, so look at the function's resource policy for an invoke permission for this API and route. A second cause is that the route's integration points at a different or deleted function, so check the integration target in the API's configuration or the SAM template. Because the function never ran, the unit tests and the log group cannot show the problem. The access log field $context.integrationErrorMessage should give the specific reason.
Exercise
Your handler passes all unit tests, but the deployed API returns 500 for GET /items/42 and the function log shows a clean run with a 200 response. What shape problem could explain this, and how do you check it?
Show answer
The returned dictionary probably has an invalid shape, for example a body that is a dictionary instead of a JSON string, or a value that API Gateway cannot parse. Add a test that asserts the body is a string, and check the access log field $context.integrationErrorMessage for the exact message.