Making Http Requests in a Node.js Lambda Function

avatar

Borislav Hadzhiev

Wed Sep 29 20216 min read

banner

Photo by Clay Banks

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 above uses the native https module, which is quite difficult to get working with promises.

In our getRequest function we make an HTTP GET request to fetch some data and return a Promise, which gets resolved on a successful request or rejected in case anything went wrong.

In our 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.

If I test the lambda function in the console we get the response data.

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, }; } };

Our 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 and on successful API response resolves with the data, otherwise rejects with the 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 our patchRequest function takes 2 parameters - the path and the body.

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

We've set the method as PATCH in the options object.

Like all other examples, the function returns a promise and resolves it on 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 for the PATCH request. Only the method in the options object is different.

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

The putRequest function returns a promise and resolves it on 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 simply send a 204 status on DELETE requests with no body, other APIs send the deleted item in the response or a success message.

Our 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee