1

The documentation states that the json should return containing a body,headers,and a status code all of which I have. However for whatever reason when I test it in API gateway it returns a malformed response.

This is the output of the method below it.

"{\"body\": 200, \"headers\": {\"Content-type\": \"application/json\"}, \"statusCode\": 200}"

def addnumbers(message, context):

    result = message['num1'] + 1
    print(result)
    resp = {
        "statusCode": 200,
         "body":  result,
        "headers": { "Content-type": "application/json"}
    }
    return (json.dumps(resp))

I am currently passing in num1=1 and it doesn't give any better error message. Any guidance would be appreciated.

Mark B
  • 139,343
  • 19
  • 240
  • 237
  • 1
    What happens when you try to return the response object directly, instead of converting it to a string with `json.dumps`? Simply `return resp`? – Mark B Oct 10 '17 at 17:49
  • Still the same issue, could it be something else affecting it aside from the code? – eternal_atom Oct 10 '17 at 17:55
  • Are you sure it is returning that response and not throwing an error? Are you checking the function's logs in CloudWatch? – Mark B Oct 10 '17 at 17:57
  • https://pastebin.com/LHZ9FH7r I was looking at the logs on the side panel to the right in the api gateway. – eternal_atom Oct 10 '17 at 18:00
  • 1
    Did you see the Python stack trace in that log? `Endpoint response body before transformations: {"stackTrace": [["/var/task/lambda_function.py", 5, "addnumbers", "result = message['num1'] + 1"]], "errorType": "KeyError", "errorMessage": "'num1'"}` – Mark B Oct 10 '17 at 18:21
  • 1
    I think I found the solution. It may not be the optimal / right one. It was because I was doing a get that it failed. I changed the operation to "ANY" then do a POST and it works fine. – eternal_atom Oct 10 '17 at 18:58
  • @eternal_atom You should add an answer to close out the issue if you've found the problem. – johnny_mac Oct 11 '17 at 01:36

1 Answers1

2

Ok buckle in for an answer.

Make sure you have proxy integration enabled on whatever resource you want in your API.

Now go to your lambda. Look at how I was previously trying to pass in num1.I was trying to get it from the "Event" or message. This is where I was tripping up. Also note (you can't do a get with a body) Rather the input to the lambda should be like this.

{ "queryStringParameters": { "input": "Whatever the input is you want the lambda to test" } }

So now that we have our test configured for the lambda we need to code the lambda itself.

I put this code within :

def lambda_handler(event, context):

number = "Hello, " + event['queryStringParameters']['input']
out = {}
out['statusCode'] = 200
out['body'] = number

return (out)

Now if you test it should be fine.

Go back to the API Gateway In the "Query Strings" Section put in input=randomname

It should now return with hello, randomname