#[SOLVED] Error 502 on get function

11 messages · Page 1 of 1 (latest)

robust sail
#

I am encountering an issue while running my API locally which invokes my GET Lambda function. Specifically, I am receiving a 502 bad gateway error and an error message saying 'Invalid lambda response received: Lambda response must be valid JSON' even after verifying that my JSON is valid using a JSON validator. Despite trying different solutions, I am still unable to resolve the issue.

def lambda_handler(event, context):
        response = table.get_item(Key={'ID': 'viewCount'})
        if "Item" in response:
                view_count = response['Item']['viewCount']
        print(view_count)
        return {
            "statusCode": 200,
                "headers": {
                        "Access-Control-Allow-Origin": "*",
                        "Access-Control-Allow-Headers": "*",
                        "Access-Control-Allow-Credentials": "*",
                        "Content-Type": "application/json",
                        "Access-Control-Expose-Headers": "*"
  },
  "body": view_count
    # "body": "Something is def wrong"
    # "body" : str(view_count)
}
worn ravine
#

You have to turn your response into json

#

Enclose it in json.dumps()

robust sail
worn ravine
#

Sorry just your return body should be json dumps

robust sail
#

Something like this: "body": json.dumps(view_count)? Or should I enclose the entire thing, json.dumps({ "body" : view_count })

worn ravine
#

so return { "statusCode": 200, "headers": {}, "body": json.dumps({"count": view_count}), }

#

then you will access the value by getting the value of count

#

in your javascript

robust sail
#

Thank you so much!