AWS lambda - API gateway : Malformed Lambda proxy

Hello everyone,
I started playing with aws lambda since 2 days, everything is new for me there (nodejs, API gateway, lambda functions).

My first idea was to take some data from my database table and return it to a web page. So I created lambda function that return me the values that I want in test phase, but when I pass by the API Gateway I’m getting the malformed lambda proxy.

I’m not sure but it’s probably because of my data’s type that my API doesn’t work.

Here’s my function code :

‘use strict’;

const AWS = require(‘aws-sdk’);
const sql = require(‘mssql’);

exports.handler = (event, context, callback) => {

const config =
{
user: ‘xxxx’,
password: ‘xxxx’,
server: ‘xxx.xxx.xxx.xxx’,
database: ‘test’,
};

const done = function (err, res)
{
callback(null, {
statusCode: err ? ‘400’ : ‘200’,
body: err ? err : res,
headers: {
‘Content-Type’: ‘application/json’,
‘Access-Control-Allow-Origin’: ‘*’
}
});
};

var path = event.pathParameters.proxy;

if (path === ‘conversations’)
{
sql.connect(config, (err) =>
{
if(err)

        {
            console.log(err);
            callback(err);
        }
        else
        {
            const req = new sql.Request();
            req.query('SELECT * FROM prsn',(error, result) => 
            {
                if(error)
                {
                    console.log(error);
                    callback(error);
                }
                else
                {
                    callback(null, result.recordset);
                    sql.close();
                }
            });
        }
    });
}
else
{
    done('No cases hit');
}
};

Someone can show me the right way to how to deal with that error please ?


Related discussions:

In the api gateway resource set up you may need to choose lambda proxy as the integration type

You need to include isBase64Encoded in your response, I believe. I banged into this problem a bit with Python3 and it finally worked when I added isBase64Encoded. The docs say it can be unspecified but as soon as I started sending that it started working.

Try:

callback(null, {
statusCode: err ? ‘400’ : ‘200’,
body: err ? err : res,
isBase64Encoded: False,
headers: {
‘Content-Type’: ‘application/json’,
‘Access-Control-Allow-Origin’: ‘*’
}
});

This is caused from a bad return value of your function. Ensure you json stringify your output body.

Oh, as a note you need to ensure that your database is closed or your function will fail. In your code if there’s error you never call sql.close, which will cause your function to time out.

PHP will close all your outstanding database connections for you when you exit PHP. Node/lambda will hang/time out waiting for that event. You can get around/suppress that behavior using a context variable that I’ve forgotten. It’s something like waitForEventDone.

This might be helpful: https://aws.amazon.com/premiumsupport/knowledge-center/malformed-502-api-gateway/

Here’s the documentation for the output format - it’s a bit hard to find:

With the Lambda proxy integration, API Gateway requires the backend Lambda function to return output according to the following JSON format:

{ “isBase64Encoded”: true|false, “statusCode”: httpStatusCode, “headers”: { “headerName”: “headerValue”, ... }, “body”: “...” }

Note “body” is a string, not an object/json
https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html

As a side note - I would keep your secrets out of the code by passing environment variables or using Parameter Store (preferred method).

I would also say check this carefully - the majority of times I have seen the malformed response error it’s been because of missing something here. Also, it can’t be said enough but make sure body is a string not json!

Hey, thanks for this note, should I write before each error callback or there is a better way to close my sql connections properly ?

Hey thanks for your help, I find that one of my error’s cause was json format but there was another things too

thanks for that best practice note !

New Secrets manager?

Hey, that’s exactly what I was looking for, the problem was that my function didn’t return the good format (in first place it wasn’t a json format) and it return only my body result and not the full output. There is how I resolv my problem :

Convert my result to json format :

body: err ? JSON.stringify(err) : JSON.stringify(res),

Return my values with done function :

req.query(‘SELECT * FROM lu_prsn’,(error, result) =>
{
if(error)
{
console.log(error);
callback(error);
}
else
{
sql.close();
done(err, result.recordset);
}
});

I would also say check this carefully - the majority of times I have seen the malformed response error it’s been because of missing something here. Also, it can’t be said enough but make sure body is a string not json!

If you need automatic credential rotation, sure. Secrets Manager is just an expensive ($.40/secret/month) layer on top of Parameter Store that can automatically rotate credentials.