Sub topic 2
Writing a handler: event, context and return values
This chapter assumes you can write basic Python, read JSON, and know how an HTTP request and response are structured. It also assumes you have an AWS account and a rough idea of what an IAM role is. The examples use Python, but the model is the same in every Lambda runtime.
What Lambda actually calls
A Lambda function is your code plus a setting that names its entry point. That setting is called the handler. In Python it has the form file.function. The value app.handler means "import app.py and call the function named handler."
Lambda calls that function with two arguments:
eventholds the input data for this invocation.contextholds information about the invocation and the runtime.
The function must accept both, even if it ignores one. A handler with the wrong number of parameters fails on every invocation with a TypeError.
The event
The event is the trigger's payload, converted from JSON into a Python dict, list, string or number. Most triggers send a dict. Its shape depends entirely on who invoked the function:
| Trigger | Where your data lives |
|---|---|
| API Gateway HTTP API | `event["body"]` (a string), plus `headers`, `queryStringParameters`, `rawPath` |
| SQS | `event["Records"]`, each with a `body` string and a `messageId` |
| S3 | `event["Records"]`, each with the bucket name and object key |
| Direct `Invoke` call | Whatever JSON the caller sent as the payload |
Lambda does not validate the event for you. Treat it as untrusted input from outside your code.
Three details about API Gateway events cause most beginner bugs:
bodyis a string, not a dict. You must calljson.loadson it.bodycan be missing orNone, for example on a GET request. Useevent.get("body") or "{}"rather thanevent["body"].- If
isBase64EncodedisTrue, the body is base64 text. This happens with binary content types, so decode it before parsing.
When you are unsure what an event looks like, print it once to CloudWatch Logs with print(json.dumps(event)). Then remove the print, because events can contain personal data.
The context object
The context describes the invocation, not its data. In Python these are the attributes you will use most:
context.aws_request_idis a unique ID for this invocation. Put it in your logs so you can find one request later.context.function_nameandcontext.function_versionidentify what is running.context.memory_limit_in_mbis the configured memory.context.log_group_nameandcontext.log_stream_nametell you where the logs go.context.get_remaining_time_in_millis()returns how many milliseconds are left before the timeout.
The last one is the most practical. A function that loops over many items can check it and stop cleanly, instead of being killed halfway through.
Return values
What Lambda does with your return value depends on how the function was invoked. The invocation types get their own chapter. For now, remember this:
- Synchronous invocation (API Gateway, a direct
RequestResponsecall): the return value is sent back to the caller. It must be JSON serializable. Returning adatetime, asetor aDecimalraises a serialization error. - Asynchronous invocation (S3, SNS,
InvocationType="Event"): the return value is discarded. Only success or failure matters. - Poll-based invocation (SQS and similar): the return value is mostly ignored. The exception is a batch response, which a later chapter covers.
For API Gateway, the return value must be an object that API Gateway can turn into an HTTP response. The safe, explicit form has three keys:
{
"statusCode": 201,
"headers": {"Content-Type": "application/json"},
"body": '{"id": "abc"}',
}body must be a string. A common mistake is returning a dict as the body. Use json.dumps for it.
If the function returns something API Gateway cannot interpret, the client gets a 5xx error and your logs show a successful invocation. That mismatch is a reliable sign of a response-format bug.
A complete handler
This handler comes from the plan for this tutorial. It parses the body, writes an item to DynamoDB and returns a response.
import json
import os
import uuid
import boto3
# Created once per execution environment and reused across invocations.
table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])
def handler(event, context):
body = json.loads(event.get("body") or "{}")
item = {"id": str(uuid.uuid4()), "item": body.get("item", "unknown")}
table.put_item(Item=item)
return {
"statusCode": 201,
"headers": {"Content-Type": "application/json"},
"body": json.dumps(item),
}Notice where each line sits:
- The imports and the
tableobject are outside the function. They run once when the execution environment starts, not on every request. The next chapters explain why this matters for speed and cost. - Everything inside
handlerruns once per invocation. TABLE_NAMEcomes from an environment variable, so the same code works in test and production without edits.- The function has no credentials in it. boto3 picks up temporary credentials from the function's execution role.
Handling bad input and errors
The handler above has a weakness. If the body is not valid JSON, json.loads raises an exception, and the client sees a generic server error for what is really the client's mistake.
You have two ways to report a failure, and they behave differently:
- Return an error response, such as
statusCode400. Lambda counts the invocation as a success. Use this for problems you expect, like bad input. - Raise an exception. Lambda marks the invocation as failed and records the error type, message and stack trace. A synchronous caller gets a function error. An asynchronous or poll-based trigger may retry. Use this for problems you did not expect.
Here is a handler that returns 400 for bad input and uses the context for logging:
import base64
import json
def response(status, payload):
return {
"statusCode": status,
"headers": {"Content-Type": "application/json"},
"body": json.dumps(payload),
}
def handler(event, context):
raw = event.get("body") or "{}"
if event.get("isBase64Encoded"):
raw = base64.b64decode(raw).decode("utf-8")
try:
body = json.loads(raw)
except json.JSONDecodeError:
return response(400, {"error": "body must be valid JSON"})
item = body.get("item") if isinstance(body, dict) else None
if not isinstance(item, str) or not item:
return response(400, {"error": "item must be a non-empty string"})
print(json.dumps({
"request_id": context.aws_request_id,
"item": item,
"ms_left": context.get_remaining_time_in_millis(),
}))
return response(200, {"item": item})The isinstance(body, dict) check matters. Valid JSON such as [1, 2] or "text" parses without error but has no .get method.
Testing a handler without AWS
A handler is a plain function, so you can call it locally. Pass a hand-built event and a stand-in for the context. Save the second handler above as validate.py and run this next to it:
from types import SimpleNamespace
from validate import handler
context = SimpleNamespace(
aws_request_id="test-123",
get_remaining_time_in_millis=lambda: 5000,
)
print(handler({"body": '{"item": "book"}'}, context))
print(handler({"body": "not json"}, context))
print(handler({}, context))The first call returns status 200. The other two return status 400. This test needs no AWS account, which is why it pays to keep AWS calls at the edges of the function and the validation logic separate.
Common mistakes
| Symptom | Likely cause |
|---|---|
| `TypeError: handler() takes 1 positional argument` | The function does not accept both `event` and `context` |
| Runtime error `Unable to import module` or `Handler not found` | The handler setting does not match the file and function name |
| Client gets 5xx but the invocation shows success | The return value is not a valid API Gateway response, for example `body` is a dict |
| `KeyError: 'body'` | The function was invoked without a body, such as a GET request or a console test |
| `Object of type Decimal is not JSON serializable` | A value read from DynamoDB was returned without conversion |
Exercise
A handler returns {"statusCode": 200, "body": {"ok": True}} behind an API Gateway HTTP API. The Lambda logs show a successful invocation, but the client receives an error. What is wrong, and how do you fix it?
Show answer
The body is a dict, but API Gateway needs a string. Return "body": json.dumps({"ok": True}). The invocation itself succeeded, so the failure appears only when API Gateway tries to build the HTTP response.
Exercise
Your handler needs to process a long list of records. Which context method helps you avoid being cut off by the timeout, and how would you use it?
Show answer
context.getremainingtimeinmillis(). Check it inside the loop, and when the value drops below a safe margin (for example 2000 ms), stop processing and either return the progress so far or save the remaining work for another invocation.
Exercise
A caller invokes your function with InvocationType "Event" and your handler returns {"statusCode": 200}. Where does that return value go?
Show answer
Nowhere. Asynchronous invocations discard the return value. Lambda only records whether the function succeeded or raised an error.