Last updated: Feb 26, 2024
Reading timeยท6 min
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.
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.
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.
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 assumes 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.
A test invocation of the Lambda function shows that the POST
request is
successful.
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.
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.
A test invocation of the Lambda function shows that the PATCH
request is
successful.
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.
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.
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.
A test invocation of the Lambda function shows that the PUT
request is
successful.
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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: