Search code examples
pythonhttpaws-lambdaaws-api-gatewayhttp-status

AWS API Gateway, Python Lambda and HTTP status


I'm struggling to understand how to setup proper http status codes and error messages using AWS API Gateway and a Lambda Function (python) as Integration type.

I'm working with a simple example, here the details:

Lambda function

def lambda_handler(event, context):

    return_json = {}
    if event["request-number"] == "":
        raise Exception("Error request-number can't be empty")
    elif event["request-number"] == "3":
        raise Exception("Value not accepted")
    else:
        return_json = {"service-activated": "TRUE"}

    return return_json

API /resourcetest POST

This is integrated with the lambda above.

Goal: return HTTP 400 and body with message Error request-number can't be empty when request-number = "".

Implementation:

  1. I've created a new method response 400
  2. In the lambda Error Regex I've mapped Error.* so to catch that string
  3. In the body mapping templates: I've created a content-type as application/json and as a template I've used (there's an hashtag symbol before set, but that screw up the formatting of this page, so I've omitted it):

    set($inputRoot = $input.path('$')) { "message" : $input.json('$.errorMessage') }

  4. I've checked to have the http status 400 in the method response (and I have it)

Test Through the AWS API Gateway console I've tested to have HTTP 400 and the message Error request-number can't be empty in the body. Good I achieved what I wanted:

enter image description here

I've decided to test also through Postman and the Chrome plugin Restlet Client and what I've got is http status 200 and error message not formatted properly:

enter image description here

Now, this is quite weird: from the AWS API Console all is good and nice, from an external service nothing work as expected.

Has anyone had to deal with something similar ?

Thanks!


Solution

  • Have you re-deployed your API?