How to Call an External REST API from AWS Lambda?

Shivanjali Nimbalkar
Intelliconnect Engineering
2 min readMay 27, 2021
  • AWS Lambda is an Amazon Web Services compute service that runs your backend code in response to events and manages compute resources for you.
  • The code running on AWS Lambda is called a Lambda function.
  • You can write your code in the integrated editor within the AWS management console OR if your code requires custom libraries, you can create a .ZIP file containing all necessary components upload it as a codebase
  • You can also select from pre-built samples or blueprints.
  • Code can be written in JavaScript using Node.js, Python, .NET, Ruby, Go, or in Java.

AWS Lambda can receive event data from multiple sources as shown below and perform various operations to provide the required response.

To create a Lambda function

  1. Sign in to the Lambda console.
  2. Choose to Create function.
  3. For Function name, enter my-function.
  4. Choose to Create function.

The default Lambda function code should look similar to the following:

exports.handler = async (event) => {
const response = {
statusCode: 200,
body: JSON.stringify(‘Hello from Lambda!’),
};
return response;
};

Now, to call an external REST API, we’ll modify the Lambda Function as given below and will invoke this Lambda function from our Client-side using AWS-SDK.

The example function returns a 200 response to clients, with data from the requested external API.

const https = require('https');
const getStatus = (defaultOptions, path, payload) => new Promise((resolve, reject) => {
const options = { ...defaultOptions, path, method: 'GET' };
const req = https.request(options, res => {
let buffer = "";
res.on('data', chunk => buffer += chunk)
res.on('end', () => resolve(JSON.parse(buffer)))
});
req.on('error', e => reject(e.message));
req.write(JSON.stringify(payload));
req.end();
})
exports.handler = async (event) => {
// TODO
const defaultOptions = {
host: event._hostname, //_hostname : example.com, passed from event as a parameter
port: 443, // or 80 for http
headers: {
'Content-Type': 'application/json',
}
}
var status_info = await getStatus(defaultOptions, event._pathname, ''); //_pathname : /user/add, passed from event as a parameter
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify(status_info),
};
return response;
};

We will pass the _hostname and _pathname from the event as parameters to the lambda function.

For e.g if the REST API URL is https://example.com/user/add then,

_hostname will be : example.com and

_pathname will be /user/add

Like this, we can call any REST API in our Lambda Function and perform any serverless operations on the response.

To know more about Lambda functions and get a hand over the complete working code, please visit our Github Repository here.

--

--