Search code examples
pythonjsonamazon-web-serviceslambdaaws-api-gateway

AWS API gateway not passing data into lambda function upon invocation


I am new to APIs and Lambda, but what I am trying to do is perform a PUT method through my API and invoke a lambda function to update my DynamoDB table. I have tested my lambda function and it works when i test it with a JSON event.

import boto3
import json


def updateScore(event, context):
    
    dynamodb_client = boto3.client('dynamodb', region_name='us-east-1')
    dynamodb_resource = boto3.resource('dynamodb', region_name='us-east-1')
    table = dynamodb_resource.Table('Highscore')
    score = event["Highscore"]
    print(event.keys())
    response = table.update_item(
     Key={'ID': 0},
     ExpressionAttributeNames = {"#hs": "Highscore"},
     UpdateExpression="SET #hs = :val1",
     ExpressionAttributeValues={":val1": score}
     )

    return {
            "statusCode": 200,
            "headers": {
                'Access-Control-Allow-Headers': 'application/json',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'PUT'
            },
            'body': event['Highscore']
        }
      

with the JSON object test event

{
  "ID": 0,
  "Highscore": 1
}

the code updates my table appropriately however, when I try to test the function through the API gateway it acts as if the event given from the gateway does not exist (I say this since in the logs it shows a Key Error on the event parameter indicating that it does not exist) I get an internal server error 502 on both the test on the AWS console and on Postman. I am sending the same data that was in the event JSON object in the body but it still would not work. looking for some guidance, Thank you.


Solution

  • Step 1.

    import boto3
    import json
    
    
    def updateScore(event, context):
        print(event) # Print the event
        dynamodb_client = ...
    

    Step 2. Read the logs, via cloudwatch, either there is nothing and there is a communication issue between the gateway and the lambda, check IAM first in that case. Or the actual event object will be there and you can copy it into the test event and run the lambda in the console to see what's going down. Step 3. Success.