- Newest
- Most votes
- Most comments
The issue you're experiencing is related to how API Gateway processes the request and passes it to your Lambda function. When using AWS_PROXY integration, API Gateway structures the event object differently than when testing directly in the Lambda console.
The error "'operation'" suggests that your Lambda function is trying to access the 'operation' key in the event object, but it doesn't exist in the structure that API Gateway is sending. With AWS_PROXY integration, your request body is actually nested inside event.body as a string, not directly accessible as event['operation'].
Here's how you can modify your Lambda function to handle requests coming from API Gateway:
import boto3 import json table_name = "count-table" dynamo = boto3.resource('dynamodb').Table(table_name) def read(payload): return dynamo.get_item(Key=payload['Key']) operations = {'read': read} def lambda_handler(event, context): try: # Check if the request is coming from API Gateway if 'body' in event and isinstance(event['body'], str): # Parse the body from API Gateway body = json.loads(event['body']) operation = body['operation'] payload = body['payload'] else: # Direct Lambda invocation operation = event['operation'] payload = event['payload'] if operation in operations: result = operations[operation](payload) # Handle Decimal serialization issue return { 'statusCode': 200, 'headers': { 'Content-Type': 'application/json' }, 'body': json.dumps(result, default=str) # Use default=str to handle Decimal } else: return { 'statusCode': 400, 'headers': { 'Content-Type': 'application/json' }, 'body': json.dumps({'error': f'Unrecognized operation "{operation}"'}) } except Exception as e: return { 'statusCode': 500, 'headers': { 'Content-Type': 'application/json' }, 'body': json.dumps({'error': str(e)}) }
Key changes:
- Added logic to check if the request is coming from API Gateway (event has a 'body' key with a string value)
- Used
default=strin json.dumps() to handle the Decimal serialization issue from DynamoDB - Added proper error handling for unrecognized operations
This should allow your function to work both when tested directly in the Lambda console and when called through API Gateway.
Also, make sure your API Gateway has the necessary permissions to invoke your Lambda function. You can check this in the Permissions tab of the Lambda console.
Sources
API Gateway fails to get a proper response body from my Lambda function | AWS re:Post
How Does API Gateway Handle the Response Returned by a Lambda Function? | AWS re:Post
Troubleshooting issues with HTTP API Lambda integrations - Amazon API Gateway
Api gatway with Lambda function | AWS re:Post
