title: AWS API Gateway with Lambda HTTP GET Request (Node.js) 502 Bad Gateway
body: <p>I'm new to AWS lambda functions and NodeJS. I'm trying to create an API Gateway call to a Lambda function that calls an external API and return some JSON data. It took me a while but I was finally able to get something to work based on this post:
  <a href="https://stackoverflow.com/questions/47404325/aws-lambda-http-post-request-node-js">AWS Lambda HTTP POST Request (Node.js)</a></p>
  <p>The problem was the API Gateway kept erroring with a 502 Bad Gateway; which turns out to be that the JSON response was malformed. In the post I referenced above everyone seem to have success with just returning the JSON as-is, but I had to follow the instructions here to fix my issue:
  <a href="https://aws.amazon.com/premiumsupport/knowledge-center/malformed-502-api-gateway/" rel="nofollow noreferrer">https://aws.amazon.com/premiumsupport/knowledge-center/malformed-502-api-gateway/</a></p>
  <p><strong>My question is:</strong> if you look at the last 10 lines of my code that finally worked I had to reformat my response, as well as use a callback in a async function. I am new to nodeJS and Lambda but it looks wrong to me, even though it works. The post I referenced seem to have much more elegant code, and I hope someone can tell me what I am doing wrong.</p>
  <pre><code>const https = require('https');
  var responseBody = {&quot;Message&quot;: &quot;If you see this then the API call did not work&quot;};
  
  const doGetRequest = () =&gt; {
  
    return new Promise((resolve, reject) =&gt; {
      const options = {
        host: 'my.host.com',
        path: '/api/v1/path?and=some&amp;parameters=here',
        method: 'GET',
        headers: {
          'Authorization': 'Bearer token for testing',
          'X-Request-Id': '12345',
          'Content-Type': 'application/json'
        }
      };
      var body='';
      //create the request object with the callback with the result
      const req = https.request(options, (res) =&gt; {
  
        res.on('data', function (chunk) {
              body += chunk;
          });
        res.on('end', function () {
           console.log(&quot;Result&quot;, body.toString());
           responseBody = body;
        });
        resolve(JSON.stringify(res.statusCode));
      });
  
      // handle the possible errors
      req.on('error', (e) =&gt; {
        reject(e.message);
      });
      //finish the request
      req.end();
    });
  };
  
  exports.handler = async (event, context, callback) =&gt; {
  await doGetRequest();
  
      var response = {
          &quot;statusCode&quot;: 200,
          &quot;headers&quot;: {
              &quot;my_header&quot;: &quot;my_value&quot;
          },
          &quot;body&quot;: JSON.stringify(responseBody),
          &quot;isBase64Encoded&quot;: false
      };
      callback(null, response);
  };
  </code></pre>