How To Run Your First AWS Lambda function in the cloud

A decade ago, cloud servers abstracted away physical servers. And now, “Serverless” is abstracting away cloud servers.

Technically, the servers are still there. You just don’t need to manage them anymore. Another advantage of going serverless is that you no longer need to keep a server running all the time. The “server” suddenly appears when you need it, then disappears when you’re done with it. Now you can think in terms of functions instead of servers, and all your business logic can now live within these functions.

In the case of AWS Lambda Functions, this is called a trigger. Lambda Functions can be triggered in different ways: an HTTP request, a new document upload to S3, a scheduled Job, an AWS Kinesis data stream, or a notification from AWS Simple Notification Service (SNS).

In this tutorial, I’ll show you how to set up your own Lambda Function and, as a bonus, show you how to set up a REST API all in the AWS Cloud, while writing minimal code.

Also Read: Why do we need to get AWS Certifications?

Note that the Pros and Cons of Serverless depend on your specific use case. So in this article, I’m not going to tell you whether Serverless is right for your particular application — I’m just going to show you how to use it.

First, you’ll need an AWS account. If you don’t have one yet, start by opening a free AWS account here. AWS has a free tier that’s more than enough for what you will need for this tutorial.

We’ll be writing the function isPalindrome, which checks whether a passed string is a palindrome or not.

const isPalindrome = (string) => {
    
  const reverse = string.split('').reverse().join('');
  const isPalindrome = (string === reverse);
    
  const result = isPalindrome ? `${string} is a Palindrome` : `${string} is not a Palindrome`;
    
  return result;
  
};

Above is an example implementation in JavaScript. Here is the link for gist on Github.

A palindrome is a word, phrase, or sequence that reads the same backward as forward, for the sake of simplicity we will limit the function to words only.

As we can see in the snippet above, we take the string, split it, reverse it and then join it. if the string and its reverse are equal the string is a Palindrome otherwise the string is not a Palindrome.

Creating the isPalindrome Lambda Function

AWS-Services

In the AWS Console go to Lambda.

AWS-Lambda

And then press “Get Started Now.”

AWS-Lambda-GetStarted

For runtime select Node.js 6.10 and then press “Blank Function.”

AWS-NodeJs

Skip this step and press “Next.”

AWS-lambda-Function

For Name type in isPalindrome, for description type in a description of your new Lambda Function, or leave it blank.

exports.handler = (event, context, callback) => {
  //some code here
  callback(error, response);
};

As you can see in the gist above a Lambda function is just a function we are exporting as a module, in this case, named handler. The function takes three parameters: event, context and a callback function.

Also Read: How to Launch a Linux Virtual Machine with Amazon EC2

The callback will run when the Lambda function is done and will return a response or an error message.For the Blank Lambda blueprint response is hard-coded as the string ‘Hello from Lambda’. For this tutorial since there will be no error handling, you will just use Null. We will look closely at the event parameter in the next few slides.

AWS-Lambda-EnvironmentVariables

Scroll down. For Role choose “Create new Role from template”, and for Role name use isPalindromeRole or any name, you like.

For Policy templates, choose “Simple Microservice” permissions.

AWS-Lambda-NewRule

For Memory, 128 megabytes is more than enough for our simple function.

As for the 3 second timeout, this means that — should the function not return within 3 seconds — AWS will shut it down and return an error. Three seconds is also more than enough.

Leave the rest of the advanced settings unchanged.

AWS-Lambda-Review

Press “Create function.”

AWS-Lambda-CreateFunction

Congratulations — you’ve created your first Lambda Function. To test it press “Test.”

AWS-Lambda-ExecutionResult

As you can see, your Lambda Function returns the hard-coded response of “Hello from Lambda.”

AWS-Lambda-Code

Now add the code from isPalindrome.js to your Lambda Function, but instead of return result use callback(null, result). Then add a hard-coded string value of abcd on line 3 and press “Test.”

AWS-Lambda-Return-Result

The Lambda Function should return “abcd is not a Palindrome.”

AWS-Lambda-Code-Return

For the hard-coded string value of “racecar”, The Lambda Function returns “racecar is a Palindrome.”

AWS-Lambda-ExecutionResult-Succeed

So far, the Lambda Function we created is behaving as expected.

In the next steps, I’ll show you how to trigger it and pass it a string argument using an HTTP request.

var express = require('express');
var app = express();

app.get('/', function(req,res) {
  res.send('hello world');
});

app.listen(3000);

If you’ve built REST APIs from scratch before using a tool like Express.js, the snippet above should make sense to you. You first create a server, and then define all your routes one-by-one.

In this section, I’ll show you how to do the same thing using the AWS API Gateway.

Creating the API Gateway

AWS-API-Gateway

Go to your AWS Console and press “API Gateway.”

Amazon-Api-Gateway

And then press “Get Started.”

AWS-CreateNewAPI

In Create new API dashboard select “New API.”

AWS-Create-New_API

For API name, use “palindromeAPI.” For description, type in a description of your new API or just leave it blank.

AWS-PlindromeAPI

Our API will be a simple one, and will only have one GET method that will be used to communicate with the Lambda Function.

In the Actions menu, select “Create Method.” A small sub-menu will appear. Go ahead and select GET, and click on the checkmark to the right.

AWS-API-Gatway_Get-Setup

For Integration type, select Lambda Function.

AWS-AddPermissiontolambdaFunction

Then press “OK.”

AWS-API-Get-MethodExecution

In the GET — Method Execution screen press “Integration Request.”

AWS-API-Get-IntegrationRequest

For Integration type, make sure Lambda Function is selected.

AWS-API-BodyMappingTemplate

For request body passthrough, select “When there are no templates defined” and then for Content-Type enter “application/json”.

AWS-API-Application-Json

In the blank space add the JSON object shown below. This JSON object defines the parameter “string” that will allow us to pass through string values to the Lambda Function using an HTTP GET request. This is similar to using req.params in Express.js.

In the next steps, we’ll look at how to pass the string value to the Lambda Function, and how to access the passed value from within the function.

AWS-API-PassedValues

The API is now ready to be deployed. In the Actions menu click “Deploy API.”

AWS-Deploy-API

For Deployment Stage select “[New Stage]”.

AWS-Deploy-API-NextStage

And for Stage name use “prod” (which is short for “production”).

AWS-API-Gateway-Prod-Stage

The API is now deployed, and the invoke URL will be used to communicate via HTTP request with Lambda. If you recall, in addition to a callback, Lambda takes two parameters: event and context.

To send a string value to Lambda you take your function’s invoke URL and add to it ?string=someValue and then the passed value can be accessed from within the function using event.string.

Modify code by removing the hard-coded string value and replacing it with event.string as shown below.

AWS-Lambda-Hard-Coded-Values

Now in the browser take your function’s invoke URL and add ?string=abcd to test your function via the browser.

Browser-Invoke-Function-URL

As you can see Lambda replies that abcd is not a Palindrome. Now do the same for racecar.

AWS-Lambda-Function-Replies

If you prefer you can use Postman as well to test your new isPalindrome Lambda Function. Postman is a great tool for testing your API endpoints, you can learn more about it here.

To verify it works, here’s a Palindrome:

Postman-Api-Tool

And here’s a non-palindrome:

Postman-non-Plindrome

Congratulations — you have just set up and deployed your own Lambda Function!

Thanks for reading!

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time
Comments

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More