Sub topic 4
Connecting a route to Lambda with proxy integration
This chapter assumes you know what a route, an integration and a stage are in an HTTP API, and that you can write a basic Python Lambda handler. It covers how a route reaches your function, what permission that requires, and what happens when the two disagree.
What an integration is
An integration is the backend that API Gateway calls when a route matches. A route has exactly one target, and that target points to an integration. Several routes can share one integration, which is how a single function can serve GET /items/{id} and POST /items.
For Lambda, HTTP APIs support one integration type: AWS_PROXY, called Lambda proxy integration. "Proxy" means API Gateway does not reshape the request or the response. It packages the whole HTTP request into a JSON event and passes it to the function. It then turns the function's return value back into an HTTP response.
This has two consequences:
- You cannot write mapping templates (VTL) to rename fields or reshape payloads. That feature exists only in REST APIs with non-proxy integrations.
- All request parsing and response building happens in your code. The next chapters cover the event and response formats in detail.
The request path
The call is synchronous. API Gateway invokes the function and holds the client connection open until the function returns or the integration times out.
API Gateway checks the route and any authorizer before it invokes Lambda. A request that matches no route, or that fails authorization, never reaches your function and costs no invocation.
The pieces you must connect
Three separate things have to line up. A missing one is the most common reason a new API fails.
- An integration of type
AWS_PROXY. It holds the function ARN and the payload format version. - A route whose target is that integration.
- A resource-based policy on the function that lets API Gateway invoke it.
The third piece is separate from the function's execution role. The execution role says what your code may call. The resource-based policy says who may call your function. API Gateway uses the second one.
Building it by hand with the AWS CLI
SAM creates all three pieces for you, as the next section shows. Doing it once with the CLI shows what SAM generates. Replace the placeholder values with your own.
REGION="us-east-1"
ACCOUNT="123456789012"
FUNCTION="items-function"
FUNCTION_ARN="arn:aws:lambda:$REGION:$ACCOUNT:function:$FUNCTION"
API_ID=$(aws apigatewayv2 create-api \
--name items-api \
--protocol-type HTTP \
--query ApiId --output text)
INTEGRATION_ID=$(aws apigatewayv2 create-integration \
--api-id "$API_ID" \
--integration-type AWS_PROXY \
--integration-uri "$FUNCTION_ARN" \
--payload-format-version 2.0 \
--query IntegrationId --output text)
aws apigatewayv2 create-route \
--api-id "$API_ID" \
--route-key "GET /items/{id}" \
--target "integrations/$INTEGRATION_ID"
aws lambda add-permission \
--function-name "$FUNCTION" \
--statement-id "apigw-get-item" \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com \
--source-arn "arn:aws:execute-api:$REGION:$ACCOUNT:$API_ID/*/GET/items/*"
aws apigatewayv2 create-stage \
--api-id "$API_ID" \
--stage-name '$default' \
--auto-deployPoints worth noticing:
--targettakes the formintegrations/<id>. The route does not store the function ARN.--payload-format-version 2.0selects the event shape. HTTP APIs also accept1.0, which matches the REST API format. The rest of this tutorial uses2.0.- The
--source-arnhas the formarn:aws:execute-api:<region>:<account>:<api-id>/<stage>/<METHOD>/<path>. The*in the stage position allows any stage. Narrowing the path makes the permission apply only to the routes you intend. - The
'$default'stage name needs single quotes so the shell does not expand it.
The same thing in SAM
In a SAM template, an HttpApi event on a function creates the integration, the route and the invoke permission in one declaration.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.13
Handler: app.handler
CodeUri: src/
Events:
GetItem:
Type: HttpApi
Properties:
Path: /items/{id}
Method: GETWhen you omit ApiId, SAM creates an implicit HTTP API and a $default stage with auto-deploy. Use an explicit AWS::Serverless::HttpApi resource, as in the topic's full template, when you need CORS, authorizers or a named stage.
What the function must return
With payload format 2.0, API Gateway is lenient about the response shape. The structured form is the safest one:
import json
def handler(event, context):
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"body": json.dumps({"ok": True}),
}The body must be a string. A frequent bug is returning "body": {"ok": True}, a dictionary. API Gateway cannot serialize that into the HTTP response and answers with a 500 error. Your function still logs a successful invocation, which makes this bug confusing.
If a function returns valid JSON that has no statusCode, format 2.0 treats the whole value as the body and assumes status 200. Do not rely on this. Explicit status codes make errors visible to clients.
Timeouts and limits
Two timeouts apply, and the shorter one wins.
| Setting | Where it is set | Limit |
|---|---|---|
| Integration timeout | The integration on API Gateway | 30 seconds by default, and 30 seconds is also the maximum for HTTP APIs |
| Function timeout | The Lambda function configuration | Up to 15 minutes |
A function timeout of 5 minutes does not help an API route. The client sees a 504 after the integration timeout while the function may keep running. Set the function timeout slightly below the integration timeout so the function fails first and logs a clear timeout message. Long jobs belong behind a queue or an asynchronous pattern, not behind a synchronous route.
When it goes wrong
The same status code can come from different causes, so check the symptom against where the evidence is.
| Symptom | Likely cause | Where to look |
|---|---|---|
| 500 `Internal Server Error`, no function log entry | Missing invoke permission, or wrong function ARN in the integration | Function resource policy (`aws lambda get-policy`) and the integration URI |
| 500, function log shows a Python traceback | Unhandled exception in the handler | CloudWatch Logs for the function |
| 500, function log shows success | Malformed response, such as a non-string `body` | The returned object in your handler |
| 504 `Gateway Timeout` | Function ran longer than the integration timeout | Function duration in logs, and downstream calls |
| 404 `Not Found` | No route matched the method and path | Route keys, and the stage the client called |
Sharing one function across routes
Pointing several routes at one function is allowed and is the pattern in this tutorial. The handler branches on event["requestContext"]["routeKey"]. It keeps deployments small and keeps related code together.
The trade-offs are real:
- One function has one memory setting, one timeout and one execution role. A route that needs write access to a table gives that access to every route in the function.
- A change to any route redeploys the whole function.
- The routing
ifchain grows. Past a handful of routes, you may prefer one function per route or a small routing library.
Start with one function per resource. Split it when routes need different permissions or different scaling behavior.
Exercise
A new HTTP API route returns 500 Internal Server Error for every request. The function's CloudWatch Logs show no invocations at all. Name the first two things to check, and say why the function's own code is probably not the cause.
Show answer
Check the function's resource-based policy (for example with aws lambda get-policy) for a statement that allows lambda:InvokeFunction from apigateway.amazonaws.com with a source ARN matching the API, and check that the integration URI holds the correct function ARN. Because the function was never invoked, no code of yours ran, so the failure happens in the connection between API Gateway and Lambda, not in the handler.
Exercise
Your handler returns {"statusCode": 200, "body": {"id": 42}} and clients get a 500, while the function logs show a successful run. What is wrong, and how do you fix it?
Show answer
The body value is a dictionary, but a proxy response requires a string. Return "body": json.dumps({"id": 42}) and, ideally, add a content-type: application/json header.