Sub topic 2
Writing a handler: event, context and return values
This chapter assumes you can write basic Python, read JSON, understand HTTP requests and responses, and have used IAM roles at a basic level. It covers the function entry point, the two objects Lambda passes to it, and what the function should return.
What a handler is
A handler is the function Lambda calls when something triggers your code. You give Lambda its location as file.function. With Handler: app.handler, Lambda imports app.py and calls its handler function.
Every Python handler takes two arguments:
eventis the input data. For Python it is usually adict, parsed from JSON.contextis an object with details about the invocation and the runtime.
The shape of event depends on the trigger. API Gateway sends an HTTP request description, SQS sends a batch of messages, and S3 sends a list of object notifications. A direct call sends whatever payload the caller provides.
A complete HTTP handler
This handler is triggered by an HTTP API. It parses the request body, writes an item to DynamoDB, and returns an API Gateway style 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),
}Three details matter here.
- The client is created outside the handler. Code at module level runs once when the execution environment starts. Warm invocations skip it, so they reuse the connection setup instead of repeating it. Later chapters cover this lifecycle.
- The body arrives as a string. API Gateway puts the request body in
event["body"]as text, so you must calljson.loads. Theor "{}"guards against a missing body. - The response is a dictionary. API Gateway expects
statusCode,headersand a stringbody. The body must be a string, which is whyjson.dumpsis used.
Reading the event
Treat the event as untrusted input. A caller controls what it contains, so validate fields before you use them.
Use .get() for optional keys so a missing field does not raise a KeyError. For API Gateway HTTP APIs, common fields include:
| Field | Contents |
|---|---|
| `event["body"]` | Request body as a string, or absent |
| `event["queryStringParameters"]` | Query parameters as a dict, or absent |
| `event["headers"]` | Request headers, lowercase names |
| `event["rawPath"]` | The request path |
If you are unsure of an event's shape, log it with print(json.dumps(event)) during development and read the output in CloudWatch Logs. Remove or reduce that logging before production, because events can contain personal data.
Using the context object
The context object describes the current invocation. These members are the ones you will use most:
context.aws_request_idis a unique ID for this invocation. Include it in logs to trace a request.context.function_nameis the name of the function.context.memory_limit_in_mbis the configured memory.context.get_remaining_time_in_millis()returns the time left before the timeout.
The last method is useful for long loops. You can stop cleanly and save progress before Lambda ends the function.
def handler(event, context):
done = []
for job in event["jobs"]:
if context.get_remaining_time_in_millis() < 2000:
break
done.append(job)
return {"processed": len(done), "request_id": context.aws_request_id}Return values
What you return depends on how the function was invoked.
| Invocation | What happens to the return value |
|---|---|
| API Gateway (HTTP API) | Must be a response dict, or the client gets an error |
| Direct synchronous call | Returned to the caller as JSON |
| Asynchronous call | Discarded, unless you configure a destination |
| SQS batch | Used only for `batchItemFailures` |
The return value must be JSON serializable. Returning a datetime or a Decimal raises an error. Convert such values to strings or numbers first. Note that DynamoDB returns numbers as Decimal, so convert them before you call json.dumps.
Raising errors
If your handler raises an exception, Lambda marks the invocation as failed. For a synchronous caller, it returns an error response. For asynchronous and poll-based sources, it triggers retry behavior that a later chapter describes.
For API Gateway, decide deliberately. If the client sent bad input, return a 400 response. If your code has a bug, an unhandled exception gives the client a 500.
def handler(event, context):
try:
body = json.loads(event.get("body") or "{}")
except json.JSONDecodeError:
return {"statusCode": 400, "body": json.dumps({"error": "invalid JSON"})}
return {"statusCode": 200, "body": json.dumps(body)}How the call flows
Common errors
KeyError: 'TABLE_NAME': the environment variable is not set. Module-level code runs at startup, so the failure appears on every invocation.- Client receives
Internal server error: the response dict is missing keys, orbodyis not a string. Object of type Decimal is not JSON serializable: convert DynamoDB numbers before serializing.Unable to import module 'app': theHandlersetting does not match the file name or function name.
Exercise
A handler for an HTTP API returns {"statusCode": 200, "body": {"ok": True}} and the client gets an error. What is wrong, and how do you fix it?
Show answer
The body value is a dict, but API Gateway needs a string. Use "body": json.dumps({"ok": True}).
Exercise
You invoke a function asynchronously and it returns a result dict. Where does the dict go, and what can you configure to use it?
Show answer
Lambda discards it, because no caller is waiting. You can configure an on-success destination to send the result to a target such as SQS or another function.