Sub topic 8
Building responses and handling errors
This chapter assumes you can write a Lambda handler in Python and know how a route reaches your function through proxy integration. It also assumes you know the version 2.0 event shape. Here you control what the caller sees, both on success and on failure.
The shape of a version 2.0 response
With proxy integration, API Gateway turns your return value into the HTTP response. A complete response is a dictionary with these keys:
| Key | Meaning |
|---|---|
| `statusCode` | Integer HTTP status code |
| `headers` | Dictionary of response headers |
| `body` | A **string**, not a dictionary |
| `isBase64Encoded` | `true` if `body` is base64 text for binary data |
| `cookies` | Optional list of `Set-Cookie` strings |
The most common mistake is returning a dictionary as body. Call json.dumps first.
If you return JSON that has no statusCode, version 2.0 assumes a 200 status and serializes your return value as the body. This is convenient for quick tests. For a real API, build every response explicitly so that status codes and headers are intentional.
Choosing status codes
Use the code that tells the client who must change something:
200or201for success, and204when there is no body.400for input the client can fix, such as malformed JSON.404when the resource or route is not found.500for your own bugs. Never return it deliberately for bad input.
Handling errors in one place
Raise small exceptions for expected failures and catch them in one wrapper. This keeps the route logic short and makes sure every error has the same JSON shape.
import json
class ApiError(Exception):
def __init__(self, status, message):
super().__init__(message)
self.status = status
self.message = message
def respond(status, body):
return {
"statusCode": status,
"headers": {"content-type": "application/json"},
"body": json.dumps(body),
}
def create_item(event):
try:
payload = json.loads(event.get("body") or "")
except json.JSONDecodeError:
raise ApiError(400, "Body must be valid JSON")
if "name" not in payload:
raise ApiError(400, "Field 'name' is required")
return respond(201, {"created": payload})
def handler(event, context):
try:
route = event["requestContext"]["routeKey"]
if route == "POST /items":
return create_item(event)
raise ApiError(404, "Not found")
except ApiError as err:
return respond(err.status, {"message": err.message})
except Exception:
print("Unhandled error", event["requestContext"].get("requestId"))
return respond(500, {"message": "Internal server error"})The last except returns a clean 500 and logs the request ID. You can then find the matching entry in CloudWatch Logs. Do not put stack traces or internal details in the response body.
What API Gateway does when you get it wrong
If your function raises an uncaught exception, or returns a malformed response such as a string statusCode, the client receives a 500 with {"message":"Internal Server Error"}. If the function runs past the integration limit of 30 seconds, the client receives a 504. In both cases your own error JSON never reaches the client, so the logs are the place to look.
Exercise
A client posts valid JSON to your route, but the response arrives as 500 Internal Server Error. The handler ends with return {"statusCode": 200, "body": {"ok": True}}. What is wrong, and how do you fix it?
Show answer
The body is a dictionary, and version 2.0 requires a string, so the response is malformed. Fix it with "body": json.dumps({"ok": True}), and add a content-type: application/json header.