Sub topic 8
Building responses and handling errors
This chapter assumes you can write a Lambda handler in Python and that you know how the version 2.0 event arrives from API Gateway. It covers what your function must return, what API Gateway does when the return value is wrong, and how to turn failures into clear HTTP status codes.
What API Gateway expects back
With a Lambda proxy integration and payload format 2.0, API Gateway turns your function's return value into the HTTP response. The full shape is a dictionary with these keys:
| Key | Type | Meaning |
|---|---|---|
| `statusCode` | integer | HTTP status code sent to the client |
| `headers` | object | Response headers, with string values |
| `body` | string | Response body. It must already be a string. |
| `isBase64Encoded` | boolean | `true` if `body` is base64 text for binary content |
| `cookies` | list of strings | One `Set-Cookie` value per entry |
Two details cause most early bugs. First, body must be a string, so you call json.dumps yourself. Returning a Python dict as body produces a 500. Second, header values must be strings, so write "content-length": "12", not 12.
The format 2.0 shortcut
Format 2.0 has a convenience that format 1.0 and REST APIs lack. If your function returns valid JSON that has no statusCode, API Gateway assumes status 200 and a content-type of application/json. It sends the returned value, serialized, as the body. Returning {"id": "42"} therefore works.
The shortcut hides your control over the status code and headers. Return the full shape for anything beyond a quick prototype.
Where errors come from
Not every error response comes from your code. Knowing which layer produced a response saves debugging time.
| Client sees | Usual layer | Typical cause |
|---|---|---|
| 400, 404, 409, 422 | Your handler | Input validation, missing item, conflict |
| 401, 403 | Authorizer or your handler | Missing or rejected credentials |
| 404 `{"message":"Not Found"}` | API Gateway | No route matches and there is no `$default` route |
| 429 `{"message":"Too Many Requests"}` | API Gateway | Throttling limit exceeded |
| 500 `{"message":"Internal Server Error"}` | Lambda or API Gateway | Unhandled exception, function timeout, or malformed response |
| 504 `{"message":"Gateway Timeout"}` | API Gateway | The integration did not answer within the API's integration timeout (up to 30 seconds) |
The 500 case is the one to understand. An exception that escapes your handler, an out-of-memory crash, a function timeout, and a malformed return value all look identical to the client. The client gets a generic body that tells it nothing, which is what you want. Only your logs tell the cases apart.
A response helper and error classes
Build responses in one place so that every route returns the same shape. Raise exceptions from deep code and convert them to responses at the top of the handler. This keeps validation code free of response plumbing.
import json
import logging
import traceback
logger = logging.getLogger()
logger.setLevel(logging.INFO)
class ApiError(Exception):
"""An error the client should see, with its HTTP status."""
def __init__(self, status, message):
super().__init__(message)
self.status = status
self.message = message
def respond(status, body, headers=None, cookies=None):
response = {
"statusCode": status,
"headers": {"content-type": "application/json", **(headers or {})},
"body": json.dumps(body, default=str),
}
if cookies:
response["cookies"] = cookies
return response
def get_item(item_id):
items = {"42": {"id": "42", "name": "widget"}}
if item_id not in items:
raise ApiError(404, f"Item {item_id} not found")
return items[item_id]
def create_item(raw_body):
try:
payload = json.loads(raw_body or "")
except json.JSONDecodeError:
raise ApiError(400, "Body must be valid JSON")
if not isinstance(payload, dict) or "name" not in payload:
raise ApiError(422, "Field 'name' is required")
return payload
def handler(event, context):
try:
route = event["requestContext"]["routeKey"]
if route == "GET /items/{id}":
return respond(200, get_item(event["pathParameters"]["id"]))
if route == "POST /items":
created = create_item(event.get("body"))
return respond(
201, created, headers={"location": "/items/new"}
)
raise ApiError(404, "Not found")
except ApiError as err:
logger.info("Client error %s: %s", err.status, err.message)
return respond(err.status, {"message": err.message})
except Exception:
logger.error("Unhandled error\n%s", traceback.format_exc())
return respond(500, {"message": "Internal server error"})
if __name__ == "__main__":
sample = {
"requestContext": {"routeKey": "GET /items/{id}"},
"pathParameters": {"id": "7"},
}
print(handler(sample, None))Running the file prints a 404 response, because item 7 does not exist. Change the id to 42 to see the 200 path.
Some choices in this code matter:
json.dumps(..., default=str)stops serialization from failing on values such asDecimal, which DynamoDB returns for numbers. Without it, the exception lands in your generic 500 branch.- The
except Exceptionbranch returns a fixed message. It writes the traceback to the log and never to the client, so stack traces, table names and file paths do not leak. - Catching
ApiErrorfirst lets you separate expected client errors from bugs. Client errors log atINFO, and bugs log atERROR, which is the level you alarm on.
Headers, cookies and binary bodies
Put each cookie in the cookies list, not in headers. Format 2.0 turns each entry into its own Set-Cookie header:
def login_response():
return {
"statusCode": 200,
"cookies": ["session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/"],
"headers": {"content-type": "application/json"},
"body": "{\"ok\": true}",
}For other headers, a dictionary holds one value per name. If you need to send several values for the same header, join them with commas in a single string.
For binary content such as images, base64-encode the bytes, decode them to text, and set isBase64Encoded to true. The client then receives the original bytes. Lambda limits a synchronous response to 6 MB, so large files belong in S3, with the API returning a presigned URL.
Choosing status codes
Use the status code to say who must change something:
- 400 means the request is malformed, such as invalid JSON or a bad query value.
- 401 means credentials are missing or invalid. 403 means the caller is known but not allowed.
- 404 means the resource does not exist. 409 means it conflicts with current state, such as a duplicate.
- 422 means the request parses but fails validation. Teams use 400 for this too. Pick one convention and apply it everywhere.
- 500 means a bug or an outage on your side. Never return 500 for bad input, because retry logic and alarms treat 5xx as your fault.
Diagnosing a 500
When a client reports a bare 500, work through these steps:
- Find the request id in the access log, or in the response if you return one.
- Search the function's CloudWatch log group for the same id or the time window. A Python traceback means an unhandled exception. A line starting with
Task timed outmeans the function exceeded itsTimeoutsetting. - If the log shows a normal run, the return value is probably malformed. Check that
bodyis a string,statusCodeis an integer, and header values are strings. - If the log group has no entry at all, the invocation never started. Check the integration and the function's resource policy.
Exercise
A handler returns {"statusCode": 200, "body": {"ok": True}} and the client receives 500 Internal Server Error, even though the function log shows no exception. What is wrong, and how do you fix it?
Show answer
The body is a dict, but API Gateway requires a string, so the response is malformed and the gateway returns 500 while the function itself succeeds. Serialize it first: "body": json.dumps({"ok": True}). Adding a content-type header of application/json is also good practice.
Exercise
A client sends invalid JSON to POST /items. Which status code should the API return, which layer should produce it, and what should happen to the log level and the response body?
Show answer
Return 400 (or 422 if you use that convention for validation). Your handler produces it by catching the parse error and raising or returning a client error. Log it at INFO, not ERROR, since it is not a bug. The body should carry a short message such as "Body must be valid JSON" and no stack trace.