Using API Gateway as a Lambda Proxy: The Definitive Guide
Understand the Lambda proxy integration, the standard and most powerful way to connect Amazon API Gateway to your AWS Lambda functions. Learn about the event payload and response format.
When you're building a serverless API on AWS, the most common pattern is to use Amazon API Gateway to create your HTTP endpoints and AWS Lambda to run your backend logic. The standard and most powerful way to connect these two services is with a Lambda proxy integration (also known as a "Lambda-proxy" integration).
Understanding this integration is the key to building robust and scalable serverless APIs. Let's break down how it works.
What is a Lambda Proxy Integration?
With a Lambda proxy integration, API Gateway passes the entire raw HTTP request to your Lambda function in a predefined JSON structure. This includes the headers, query string parameters, path parameters, and the request body. Your Lambda function is then responsible for interpreting this request and returning a response in a specific JSON format that API Gateway can understand and transform back into an HTTP response.
This is a simple but incredibly powerful pattern. It means your Lambda function has full control over the response, including the status code, headers, and body. You are not limited by any mapping templates or transformations in API Gateway.
The Event Payload: What Lambda Receives
When a client makes a request to your API Gateway endpoint, your Lambda function is invoked with a JSON event that looks something like this:
{
"resource": "/users/{id}",
"path": "/users/123",
"httpMethod": "GET",
"headers": {
"Accept": "*/*",
"Authorization": "Bearer ...",
"Host": "..."
},
"queryStringParameters": {
"include_details": "true"
},
"pathParameters": {
"id": "123"
},
"requestContext": {
"accountId": "...",
"identity": {
"sourceIp": "..."
}
},
"body": null, // or a stringified JSON body for POST/PUT
"isBase64Encoded": false
}
Your Lambda function's handler receives this entire object. You can then parse it to get all the information you need:
httpMethod
: The HTTP verb used (GET, POST, etc.).pathParameters
: Any parameters from the URL path (e.g.,{id}
).queryStringParameters
: Any parameters from the query string.headers
: All the HTTP headers.body
: The request body as a string (you'll need to JSON-parse it if you're expecting JSON).
The Response Format: What Lambda Must Return
For the integration to work, your Lambda function must return a JSON object with a specific structure that API Gateway expects:
{
"isBase64Encoded": false,
"statusCode": 200,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
"body": "{\"message\": \"Hello from Lambda!\", \"userId\": 123}"
}
Let's look at the key parts:
statusCode
: The HTTP status code you want to return (e.g., 200, 404, 500).headers
: A JSON object of the response headers you want to set.body
: The response body as a string. This is a crucial point. If you want to return a JSON object, you must serialize it into a string first (e.g., withjson.dumps()
in Python orJSON.stringify()
in Node.js).
A Practical Example (Python)
Here's a simple Python Lambda function that demonstrates how to handle a proxy event and return a valid proxy response.
import json
def handler(event, context):
# Extract the user ID from the path parameters
try:
user_id = event['pathParameters']['id']
except (KeyError, TypeError):
return {
'statusCode': 400,
'body': json.dumps({'error': 'User ID is missing in the path.'})
}
# Your business logic to fetch the user
user_data = {
'userId': user_id,
'name': 'Alice',
'email': 'alice@example.com'
}
# Return a successful response
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json'
},
'body': json.dumps(user_data) # The body must be a string
}
Why is This the Standard?
- Flexibility and Control: It gives your backend code full control over the entire HTTP response. You can dynamically set status codes, headers, and the body based on your business logic.
- Simplicity: It's a simple, predictable contract between API Gateway and Lambda. You don't need to learn the complex and often confusing VTL (Velocity Template Language) for mapping templates.
- Framework Support: All major serverless frameworks (like AWS SAM, Serverless Framework, and AWS CDK) use the Lambda proxy integration as their default, and they provide helpers to make working with it even easier.
Conclusion
The Lambda proxy integration is the cornerstone of modern serverless API development on AWS. By understanding the simple JSON contract for the event and the response, you can build powerful, flexible, and scalable APIs where your Lambda function has complete control over the HTTP interaction. For any new API Gateway endpoint that triggers a Lambda function, this should be your default choice.