1
votes

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.

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
Still the same issue, could it be something else affecting it aside from the code?eternal_atom
Are you sure it is returning that response and not throwing an error? Are you checking the function's logs in CloudWatch?Mark B
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
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

1 Answers

2
votes

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