Search code examples
python-3.xamazon-web-servicesaws-lambdaapi-gateway

return payload for a API Gateway AWS


I have created a lambda function in Python 3.6 to return few records to an API gateway. the return standard according to documentation must be:

{
  "isBase64Encoded" : "boolean",
  "statusCode": "number",
  "headers": { ... },
  "body": "JSON string"
}

However, I need to return the data cached from a list and parsed to a JSON format to returned in the required format but it's not going thru, apparently, I can't assign a variable to body:

def lambda_handler(event, context):

   if event["httpMethod"] == "GET":
       param1 = event["queryStringParameters"]["param1"]
       param2 = event["queryStringParameters"]["param2"]


   info = redshift_get_output(param1,param2)
   payload = json.dumps(info)

   print(payload)

   outcome = {
    "isBase64Encoded": 'false',
    "statusCode": 200,
    "headers": { "header": "headerValue" },
    "body": payload
    }

   return outcome

When I run it like that I get in my API Gateway execution the success message but the body doesn't contain anything :(

enter image description here

Someone has a clue about how could I figure this out, please. thanks so much


Solution

  • I have finally figured this out. The thing is that even if I apply a casting method for my payload to JSON the string that was returning always has at the beginning and at the end the square brackets [].

    I created a customer replace function to delete the brackets and pass to my return function the payload without [].

    Script:

    def replace_all(text, dic):
        for i, j in dic.items():
            text = text.replace(i, j)
        return text
    
    
    def lambda_handler(event, context):
    
       if event["httpMethod"] == "GET":
           param1 = event["queryStringParameters"]["param1"]
           param2 = event["queryStringParameters"]["param2"]
    
    
       rep = {"[": "", "]": ""} 
       info = redshift_get_output(param1,param2)
       payload = json.dumps(info)
       payload = replace_all(payload,rep)
    
    
       print(payload)
    
    
       outcome = {
        "isBase64Encoded": 'false',
        "statusCode": 200,
        "headers": { "header": "headerValue" },
        "body": json.loads(payload)
        }
    
       return outcome
    

    thanks so much