Python Lambda Function returning KeyError

Question:

Currently trying to create a (simple) Lambda function in AWS using Python 3.8:

import json
import urllib3

def lambda_handler(event, context):
    status_code = 200
    array_of_rows_to_return = [ ]
    http = urllib3.PoolManager()

    try:
        event_body = event["body"]
        payload = json.loads(event_body)
        rows = payload["data"]

        for row in rows:

            row_number = row[0]
            from_currency = row[1]
            to_currency = row[2]
            
            response = http.request('GET','https://open.er-api.com/v6/latest/'+from_currency)
            response_data = response.data.decode('utf8').replace("'", '"')
            data = json.loads(response_data)
    
            exchange_rate_value = data['rates'][to_currency]

            output_value = [exchange_rate_value]
            row_to_return = [row_number, output_value]
            array_of_rows_to_return.append(row_to_return)

        json_compatible_string_to_return = json.dumps({"data" : array_of_rows_to_return})

    except Exception as err:
        status_code = 400
        json_compatible_string_to_return = event_body

    return {
        'statusCode': status_code,
        'body': json_compatible_string_to_return
    }

When I deploy/attempt to test the function from within Lambda, I receive the following error/output message:

"errorMessage": "local variable ‘event_body’ referenced before assignment",
"errorType": "UnboundLocalError"

I don’t think it’s my code as the instructor in the tutorial was able to run his successfully without any changes. Could someone p[lease help me determine what may be going on please?

Event_JSON below:

{
  "data": [
    [
      0,
      "USD",
      "INR"
    ]
  ]
}

**Update: The Lambda function now returns the following: **

{
  "statusCode": 200,
  "body": "{"data": [[0, [82.920013]]]}"
}

However, when I am trying to test the Amazon API Gateway implementation using the sample ‘Request Body’, I am receiving the following output:

{"resource": "/", "path": "/", "httpMethod": "POST", "headers": null, "multiValueHeaders": null, "queryStringParameters": null, "multiValueQueryStringParameters": null, "pathParameters": null, "stageVariables": null, "requestContext": {"resourceId": "[removed]", "resourcePath": "/", "httpMethod": "POST", "extendedRequestId": "[requestid]", "requestTime": "27/Feb/2023:25:13:38 +0000", "path": "/", "accountId": "12345678", "protocol": "HTTP/1.1", "stage": "test-invoke-stage", "domainPrefix": "testPrefix", "requestTimeEpoch": 36018142, ....{"cognitoIdentityPoolId": null, "cognitoIdentityId": null, "apiKey": ......."cognitoAuthenticationProvider": null, "user": "1234567"}, .... "body": "{rn     "data":rn         [rn             [0,"USD", "INR"]rn         ]rn }", "isBase64Encoded": false}

Request body below:

{
     "data":
         [
             [0,"USD", "INR"]
         ]
 }
Asked By: John Wick

||

Answers:

You do not have body in your sample event.

This code was tested with your event:

import json
import urllib3

def lambda_handler(event, context):
    status_code = 200
    array_of_rows_to_return = [ ]
    http = urllib3.PoolManager()

    try:
        rows = event["data"]

        for row in rows:

            row_number = row[0]
            from_currency = row[1]
            to_currency = row[2]
            
            response = http.request('GET','https://open.er-api.com/v6/latest/'+from_currency)
            response_data = response.data.decode('utf8').replace("'", '"')
            data = json.loads(response_data)
    
            exchange_rate_value = data['rates'][to_currency]

            output_value = [exchange_rate_value]
            row_to_return = [row_number, output_value]
            array_of_rows_to_return.append(row_to_return)

        json_compatible_string_to_return = {"data" : array_of_rows_to_return}

    except Exception as err:
        status_code = 400
        json_compatible_string_to_return = event

    return {
        'statusCode': status_code,
        'body': json.dumps(json_compatible_string_to_return)
    }
Answered By: Alex Chadyuk