【问题标题】:Lambda function works, but fails when invoked through the API gatewayLambda function works, but fails when invoked through the API gateway
【发布时间】:2022-12-02 03:49:38
【问题描述】:

I have a lambda function that puts items in a dynamodb table. It works perfectly fine with test events.

import boto3

class DBupload:

def __init__(self):
    client = boto3.resource('dynamodb')
    self.table=client.Table('labels')
    
def Create_data(self,event):
    response=self.table.put_item(
        Item={
            'instanceID' : event['id'],
            'imageID' : event['imageid'],
            'labels' : event['labels']
        }
    )
    return{
        'statusCode' : response['ResponseMetadata']['HTTPStatusCode'],
        'body' : 'Record ' + event['id'] + ' added'
    }

def lambda_handler(event, context):
if event:
    instance =  DBupload()
    if event['tasktype']  == "create":
        create_result =  instance.Create_data(event['data'])
        return create_result
    else :
        return {
            'statusCode': '404',
            'body': 'Not found'
        }

I make a REST API gateway, create a resource, and a POST method, with proxy, and I enable IAM and API key, before deploying it. I then go to usage plans, and add the stage to the usage plan, then deploy once more for good measure.

When I send the exact same request now, through Postman, it throws an Internal Server Error. I can send it through the API Gateway testing function which bypasses auth, and it gives me the following error log

Lambda execution failed with status 200 due to customer function error: 'tasktype'. Method completed with status: 502

So it looks like it is NOT an API error because the error log references the customer function in lambda. But the Lambda function works perfectly fine when I send my item in as a test-event through lambda. What gives?

Here is the test event btw

{
"tasktype":"create",
"data":{
   "id":"testinsanceid",
   "imageid":"testimageid",
   "labels":{
      "labeltype1":"labelname1",
      "labeltype2":"labelname2"
   }
}

}

【问题讨论】:

  • At the start of the lambda_handler() function, add print(event) to see what the eventactuallycontains. It probably isn't what you expect. You can view the output in CloudWatch Logs (via the function's Monitor tab).

标签: amazon-web-services rest aws-lambda amazon-dynamodb aws-api-gateway


【解决方案1】:

Try

if 'tasktype' in event and event['tasktype']  == "create":

This will ensure you're not taking a dependency on something that doesn't exist.

Also print(event) will allow you to ensure the event object is what you expect.

【讨论】:

    猜你喜欢
    • 2022-12-19
    • 2022-12-02
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 2022-11-09
    • 2022-12-02
    相关资源
    最近更新 更多