Making Http Requests in a Node.js Lambda Function

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Table of Contents #

  1. Make an Http GET Request in a Node.js Lambda
  2. Make an Http POST Request in a Node.js Lambda
  3. Make an Http PATCH Request in a Node.js Lambda
  4. Make an Http PUT Request in a Node.js Lambda
  5. Make an Http DELETE Request in a Node.js Lambda

Make an Http GET Request in a Node.js Lambda #

Let's look at an example HTTP GET request made in a Node.js lambda function.

We'll use the native https node library so we don't have to add any dependencies.

I'll post the entire code snippet and then we'll go over the code.

The code for this article is available on GitHub
get-request.js
const https = require('https'); function getRequest() { const url = 'https://reqres.in/api/users'; return new Promise((resolve, reject) => { const req = https.get(url, res => { let rawData = ''; res.on('data', chunk => { rawData += chunk; }); res.on('end', () => { try { resolve(JSON.parse(rawData)); } catch (err) { reject(new Error(err)); } }); }); req.on('error', err => { reject(new Error(err)); }); }); } exports.handler = async event => { try { const result = await getRequest(); console.log('result is: 👉️', result); // 👇️️ response structure assume you use proxy integration with API gateway return { statusCode: 200, headers: {'Content-Type': 'application/json'}, body: JSON.stringify(result), }; } catch (error) { console.log('Error is: 👉️', error); return { statusCode: 400, body: error.message, }; } };

The example uses the native https module, which is quite difficult to get working with promises.

The getRequest function makes an HTTP GET request to fetch some data and returns a Promise.

The Promise gets resolved on a successful request or rejected in case anything went wrong.

In the handler function, we simply await the GET request in a try/catch block and return a response.

Your lambda function's response structure might vary. This example assumes that you're using an API Gateway with proxy integration.

Here's the output from testing the lambda function in the console.

http get response

Make an Http POST Request in a Node.js Lambda #

Let's look at an example HTTP POST request made in a Node.js lambda function.

The code uses the native https node library.

I'll post the entire code snippet and then we'll go over it.

The code for this article is available on GitHub
post-request.js
const https = require('https'); function postRequest(body) { const options = { hostname: 'reqres.in', path: '/api/users', method: 'POST', port: 443, // 👈️ replace with 80 for HTTP requests headers: { 'Content-Type': 'application/json', }, }; return new Promise((resolve, reject) => { const req = https.request(options, res => { let rawData = ''; res.on('data', chunk => { rawData += chunk; }); res.on('end', () => { try { resolve(JSON.parse(rawData)); } catch (err) { reject(new Error(err)); } }); }); req.on('error', err => { reject(new Error(err)); }); // 👇️ write the body to the Request object req.write(JSON.stringify(body)); req.end(); }); } exports.handler = async event => { try { const result = await postRequest({ name: 'John Smith', job: 'manager', }); console.log('result is: 👉️', result); // 👇️️ response structure assume you use proxy integration with API gateway return { statusCode: 200, headers: {'Content-Type': 'application/json'}, body: JSON.stringify(result), }; } catch (error) { console.log('Error is: 👉️', error); return { statusCode: 400, body: error.message, }; } };

The postRequest function takes the body for the request as an argument.

The options object has a port argument, which should be set to 443 for HTTPS requests and 80 for HTTP requests.

The function returns a Promise. On a successful API response, the Promise resolves with the data, otherwise it rejects with an error.

Your lambda function's response structure might vary. This example assumes that you're using an API Gateway with proxy integration.

A test invocation of the lambda function shows that the POST request is successful.

http post response

Make an Http PATCH Request in a Node.js Lambda #

Let's look at an example HTTP PATCH request made in a Node.js lambda function.

I'll post the entire code snippet and then we'll go over the code.

The code for this article is available on GitHub
patch-request.js
const https = require('https'); function patchRequest(path, body) { const options = { hostname: 'reqres.in', // 👇 specify path e.g. /api/users/2 path: path, method: 'PATCH', port: 443, // 👈️ replace with 80 for HTTP requests headers: { 'Content-Type': 'application/json', }, }; return new Promise((resolve, reject) => { const req = https.request(options, res => { let rawData = ''; res.on('data', chunk => { rawData += chunk; }); res.on('end', () => { try { resolve(JSON.parse(rawData)); } catch (err) { reject(new Error(err)); } }); }); req.on('error', err => { reject(new Error(err)); }); // 👇️ write body on request object req.write(JSON.stringify(body)); req.end(); }); } exports.handler = async event => { try { const result = await patchRequest(`/api/users/2`, { name: 'Jimmy Smith', job: 'programmer', }); console.log('result is: 👉️', result); // 👇️️ response structure assume you use proxy integration with API gateway return { statusCode: 200, headers: {'Content-Type': 'application/json'}, body: JSON.stringify(result), }; } catch (error) { console.log('Error is: 👉️', error); return { statusCode: 400, body: error.message, }; } };

The PATCH request is similar to the POST request. This time, the patchRequest function takes 2 parameters - the path and the body.

The path is the part after the hostname, e.g. - /api/users/2.

We set the method as PATCH in the options object.

Like in all other examples, the function returns a Promise and resolves it on a successful API response or rejects it in case of an error.

Your lambda function's response structure might vary. This example assumes that you're using an API Gateway with proxy integration.

A test invocation of the lambda function shows that the PATCH request is successful.

http patch response

Make an Http PUT Request in a Node.js Lambda #

Let's look at an example HTTP PUT request made in a Node.js lambda function.

We'll use the native https node library so we don't have to add any dependencies.

The difference between the PATCH and PUT examples is the value of the method property in the options object.

I'll post the entire code snippet and then we'll go over the code.

The code for this article is available on GitHub
put-request.js
const https = require('https'); function putRequest(path, body) { const options = { hostname: 'reqres.in', // 👇 specify path e.g. /api/users/2 path: path, method: 'PUT', port: 443, // 👈️ replace with 80 for HTTP requests headers: { 'Content-Type': 'application/json', }, }; return new Promise((resolve, reject) => { const req = https.request(options, res => { let rawData = ''; res.on('data', chunk => { rawData += chunk; }); res.on('end', () => { try { resolve(JSON.parse(rawData)); } catch (err) { reject(new Error(err)); } }); }); req.on('error', err => { reject(new Error(err)); }); // 👇️ write body on request object req.write(JSON.stringify(body)); req.end(); }); } exports.handler = async event => { try { const result = await putRequest(`/api/users/2`, { name: 'Bob Jones', job: 'accountant', }); console.log('result is: 👉️', result); // 👇️️ response structure assume you use proxy integration with API gateway return { statusCode: 200, headers: {'Content-Type': 'application/json'}, body: JSON.stringify(result), }; } catch (error) { console.log('Error is: 👉️', error); return { statusCode: 400, body: error.message, }; } };

The code for the PUT request is almost the same as the code for the PATCH request. The only difference is the value of the method property in the options object.

The path is the part after the hostname, e.g. - /api/users/2.

The putRequest function returns a Promise and resolves it on a successful API response or rejects it in case of an error.

Your lambda function's response structure might vary. This example assumes that you're using an API Gateway with proxy integration.

A test invocation of the lambda function shows that the PUT request is successful.

http put response

Make an Http DELETE Request in a Node.js Lambda #

Let's look at an example HTTP DELETE request made in a Node.js lambda function.

I'll post the entire code snippet and then we'll go over the code.

The code for this article is available on GitHub
delete-request.js
const https = require('https'); function deleteRequest(path) { const options = { hostname: 'reqres.in', // 👇 specify path e.g. /api/users/2 path: path, method: 'DELETE', port: 443, // 👈️ replace with 80 for HTTP requests headers: { 'Content-Type': 'application/json', }, }; return new Promise((resolve, reject) => { const req = https.request(options, res => { let rawData = ''; res.on('data', chunk => { rawData += chunk; }); res.on('end', () => { try { // 👇️ It's possible that your API has no response for DELETE requests // If so, remove `JSON.parse(rawData)` and simply resolve() resolve(JSON.parse(rawData)); } catch (err) { reject(new Error(err)); } }); }); req.on('error', err => { reject(new Error(err)); }); req.end(); }); } exports.handler = async event => { try { const result = await deleteRequest(`/api/users/2`); console.log('result is: 👉️', result); // 👇️️ response structure assume you use proxy integration with API gateway return { statusCode: 200, headers: {'Content-Type': 'application/json'}, body: JSON.stringify(result), }; } catch (error) { console.log('Error is: 👉️', error); return { statusCode: 400, body: error.message, }; } };

The deleteRequest function only takes the path as a parameter.

Some APIs send a 204 status on DELETE requests with no body. Other APIs send the deleted item in the response or a success message.

The example HTTP request assumes that the API has a response value.

In the res.on('end') callback, we try to parse the response from the API. This would fail if the API has no response value.

If that's the case with your API, simply resolve() instead of resolve(JSON.parse(rawData)).

Your lambda function's response structure might vary. This example assumes that you're using an API Gateway with proxy integration.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.