Writing a Lambda Backend
What your function receives from API Gateway, and exactly what it must return.
1 min read
With a Lambda proxy integration (the default for HTTP APIs), API Gateway passes the whole HTTP request to your
function as event, and turns whatever you return into the HTTP response.
For HTTP APIs, the useful parts of event are:
event["requestContext"]["http"]["method"]:GET,POST, …event["rawPath"]: e.g./notes/abc123event.get("pathParameters"): e.g.{"id": "abc123"}event.get("queryStringParameters"): e.g.{"limit": "10"}event.get("body"): the request body as a string, so parse JSON yourself
Try it
api_handler.py
import json
def respond(status, body):
return {
"statusCode": status,
"headers": {"Content-Type": "application/json"},
"body": json.dumps(body), # body must be a string
}
def lambda_handler(event, context):
method = event["requestContext"]["http"]["method"]
params = event.get("pathParameters") or {}
if method == "GET" and "id" in params:
return respond(200, {"noteId": params["id"], "summary": "Buy groceries for the week."})
if method == "POST":
data = json.loads(event.get("body") or "{}")
if "text" not in data:
return respond(400, {"error": "Missing 'text'"})
return respond(201, {"received": data["text"]})
return respond(404, {"error": "Not found"})Watch out
Return body as a string (use json.dumps). Returning a raw dict, forgetting statusCode, or letting an
exception escape gives the caller a confusing 500 Internal Server Error. Check CloudWatch Logs for the real
error.
Key takeaways
- With proxy integration, `event` is the full HTTP request and your return value is the response.
- Always return statusCode, headers, and a string body.
- The request body arrives as a string, so parse it with json.loads.
Check your understanding
Pick an answer to see the explanation.
1. Your handler returns {"statusCode": 200, "body": {"ok": true}}. What's wrong?