POSTing data to a URL with AWS Lambda

Originally posted on 2022-11-22

NOTE: This code is from someone else’s blog. The reference to that post is in the code. I only made modifications to let you specify the hostname, path, and data from the Lambda event.

Lambda is the glue that ties everything together. If you want to do some quick and dirty stuff at some point you’ll have a system that integrates with Lambda that you want to grab data from and POST it somewhere else.

When I did this I figured it’d be fast. But I was wrong as usual. Python runtimes don’t come with requests. The latest Node.JS runtime doesn’t work with the code samples you’ll find everywhere that use the require keyword. Change it to import you say! No. That doesn’t work either.

Never waste your time on this. Use the Node.JS 14 runtime with this code:

// Borrowed and modified from: https://thetldr.tech/how-to-make-https-post-request-using-native-https-package-in-nodejs/
const https = require('https')

exports.handler = async function (event) {
    let hostname = event['hostname']
    let data = event['data']
    let path = event['path']
    const options = {
        hostname: hostname,
        port: 443,
        path: path,
        method: 'POST'
    };
    return new Promise((resolve, reject) => {
        const req = https.request(options, (res) => {
            let body = '';
            res.on('data', (chunk) => {
                body += chunk;
            });

            res.on('end', () => {
                console.log(body)
                if (res.statusCode / 2 === 100) {
                    console.log('success')
                    resolve('Success');
                } else {
                    console.log('failed')
                    resolve('Failure');
                }
            });
            res.on('error', () => {
                console.log('error');
                reject(Error('HTTP call failed'));
            });
        });
        // The below 2 lines are most important part of the whole snippet.
        req.write(data);
        req.end();
    })
}