Search code examples
amazon-web-servicesaws-lambdaaws-api-gatewaypython-3.7aws-serverless

API Gateway Malformed Lambda proxy response in python


I created a lambda function with serverless. I tested my lambda function with lambda console and it worked fine. But I get Endpoint response body before transformations: null and Execution failed due to configuration error: Malformed Lambda proxy response when I tried to call my API endpoint for this function.

This is my serverless.yml

org: orgname
app: appname
service: report

provider:
 name: aws
 runtime: python3.7
 stage: ${opt:stage,'dev'}
 timeout: 120

role: arn:aws:iam::xxxxxxxx:role/rolexxxx

plugins:
 - serverless-python-requirements

functions:
 reportgen:
  handler: xlsx_generator.main
  events:
   - http:
      path: main
      method: get
      cors: true

custom:
 pythonRequirements:
  dockerizePip: true

package:
  exclude:
    - node_modules/**
    - venv/**

and this is snippet from xlsx_generator.py:

def main(event, context):
    log.basicConfig(level=log.DEBUG)

    if "queryStringParameters" in event.keys() and 'start_date' in event["queryStringParameters"].keys():
        if "end_date" in event["queryStringParameters"].keys():
            end_date = event["queryStringParameters"]['end_date']
        else:
            end_date = event["queryStringParameters"]['start_date']
        try:
            generate(event["queryStringParameters"]['start_date'],
                     end_date,
                     event["queryStringParameters"]['output'])
        except (ClientError, Exception, RuntimeError) as e:
            raise e
    else:
        body = json.dumps({
            "message": "Missing parameter",
            "event": event
        })
        return {
            "isBase64Encoded": False,
            "statusCode": 400,
            "headers": {
                "Access-Control-Allow-Origin": '*'
            },
            "body": body
        }

and I called my endpoint with addition for query string parameter: ?start_date=2019-11-1&end_date=2019-11-30&output=reporthugree.xlsx.

I have no idea why I still got Malformed Lambda proxy response when my function already returned response with the format from here. I am new to this whole AWS matter, please explain to me if there is something wrong.


Solution

  • it turns out my handler function, the main function, does not contain a return value from the generate function so the lambda gives null value as response. This null response will cause a malform lambda proxy response when the integration proxy attempts to transform it to API Gateway response. When you activate Lambda proxy integration make sure your function always return a valid response format according to this. it will save your time.

    I found out that my question is kind of duplicate from this