0

im trying to use AWS api gateway proxy integration with lambda to make an external api call, and i want to return the response as is back to the api gateway .

when i am executing my lambda with custom event every thing works fine , but when im trying to test it with api gateway i get an error.

event example:

{
  "requestType": "somedata",
  "requestID": "somedata",
  "createMagicLink": {
    "id": "somedata",
    "phone": "somedata",
    "urlID": "somedata",
    "callID": "somedata",
    "caller": "somedata",
    "toSendSMS": somedata
  }
}

lambda example :

import requests
import json


def lambda_handler(event, context):
    
    url = "https://someUrl"
    headers = {"Accept": "application/json","API-TOKEN": "someToken", "content-type":"application/json"}
    data = event

                
    response = requests.post(url, headers=headers, json=data)
    json_response = response.json()
    json_obj = json_response['response']

    return {
        "isBase64Encoded": 'false',
        "statusCode": 200,
        "body": json_obj
        }

lambda response , works fine :

{
  "isBase64Encoded": "false",
  "statusCode": 200,
  "body": {
    "status": "0",
    "GUID": "******",
    "magicURL": "someUrl",
    "errorMessage": ""
  }
}

when im trying to execute through api gateway post request im getting an internal server error 502 (ive changed the data var in my lambda function to data = event['body'] to catch the event from api gateway)

Sat Feb 25 14:40:58 UTC 2023 : Endpoint response body before transformations: {"errorMessage": "'response'", "errorType": "KeyError", "stackTrace": ["  File \"/var/task/index.py\", line 14, in lambda_handler\n    json_obj = json_response['response']\n"]}
Sat Feb 25 14:40:58 UTC 2023 : Lambda execution failed with status 200 due to customer function error: 'response'. Lambda request id: *
Sat Feb 25 14:40:58 UTC 2023 : Method completed with status: 502

what am i missing ?

1 Answer 1

0

solved by adding json.loads(event['body']) and json.dumps(json_obj) to the lambda function

import requests
import json


def lambda_handler(event, context):
    
    url = "https://someUrl"
    headers = {"Accept": "application/json","API-TOKEN": "someToken", "content-type":"application/json"}
    data = json.loads(event['body'])

                
    response = requests.post(url, headers=headers, json=data)
    json_response = response.json()
    json_obj = json_response['response']

    return {
        "isBase64Encoded": 'false',
        "statusCode": 200,
        "body": json.dumps(json_obj)
    }

I hope it will help someone

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.