DEV Community

Cover image for HTTP Get and Delete from AWS Lambda
Prabusah
Prabusah

Posted on

HTTP Get and Delete from AWS Lambda

TL;DR

Use Node.js runtime "https" library to perform HTTP operations in AWS Lambda.

Problem:

Node.js developers tend to use axios, node-fetch or other modules to make HTTP calls like Get, Delete, Post etc.
Though same approach works in AWS Lambda (Node.js), but these 3rd party modules adds extra cold start time.

Solution:

Node.js runtime's https library can be used to trigger HTTP Get, Delete and Post etc.

Code block 1

const http = require('https');
let callHttpMethod = function (/* Pass params as needed */) {
    const headers = {
        'Content-type': 'application/json',
        Authorization: 'Bearer authCode'
    }

    let options={
        host: '/* HOST NAME */',
        path: '/* PATH */',
        method: '/* GET or DELETE */', 
        headers: headers
    };

    const promise = new Promise((resolve, reject) => {
        let req = http.request(options, (res) => {
            const chunks = []; 
            res.on('data', chunk => chunks.push(chunk));
            res.on('error', reject); 
            res.on('end', () => {
                const { statusCode, headers } = res;
                const validResponse = statusCode > 200 && statusCode <= 299; 
                const body = chunks.join('');
                if (validResponse) resolve({ statusCode, headers, body }); 
                else reject(new Error(`Request failed. status: $statusCode), body: $(body)`));
            });
        });
        req.end();
        req.on('error', reject);
    });
    return promise;
};

let to = function (promise) {
  return promise.then(data => {
    return [null, data];
  }).catch(err => [err]);
};

let [err, data] = await to(callHttpMethod(/* Pass params as needed */));
Enter fullscreen mode Exit fullscreen mode

The "Code block 1" works only for Get and Delete methods (not works for Post operation).

I will update this blog with Post operation code.

Use Node.js runtime libs wherever required to save the size of AWS Lambda code that may help saving the cost as well.

Image by Miguel Á. Padriñán from Pixabay

Top comments (0)