How to Write Your First AWS Lambda Function

Mike Mackrory is a guest contributor for the Runscope blog. If you're interested in sharing your knowledge with our readers, we would love to have you! Please fill out this short form and we'll get in touch with you.

Have you been looking for a quick and straightforward guide to writing your first AWS Lambda function? If so, we have got you covered. This article explains everything you need to know to create your first Lambda function, and how to upload and run it in the AWS Cloud.

AWS Lambda in a Nutshell

AWS Lambda is a serverless computing platform that allows engineers to create a small function, configure the function in the AWS console, and have the code executed without the need to provision servers — paying only for the resources used during the execution. As many organizations move towards implementing serverless architectures, AWS Lambda would be the central building block they'll use.

Anatomy of a Lambda Function

To understand how to write a Lambda function, you have to understand what goes into one.

A Lambda function has a few requirements. The first requirement you need to satisfy is to provide a handler. The handler is the entry point for the Lambda. A Lambda function accepts JSON-formatted input and will usually return the same.

The second requirement is that you'll need to specify the runtime environment for the Lambda. The runtime will usually correlate directly with the language you selected to write your function.

The final requirement is a trigger. You can configure a Lambda invocation in response to an event, such as a new file uploaded to S3, a change in a DynamoDB table, or a similar AWS event. You can also configure the Lambda to respond to requests to AWS API Gateway, or based on a timer triggered by AWS Cloudwatch.

You can even set up Lambda functions to respond to events generated by Alexa, but that's well beyond the scope of this article.

Language Options

You can create your AWS Lambda function using any of a growing list of supported languages:

I use Java for the Lambda functions I write, and although I've noticed a slight lag if the function hasn't been invoked for 10 or 15 minutes, I haven't seen much of a performance difference. If performance and consistency are concerns, then you might want to check out this post comparing performance between Node.js, Java, C#, and Python.

Our Use Case

For the Lambda functions we're going to create today, let's do something a little more mathematical than a simple Hello World application. Let's pass a couple of numbers into the function, and have it return the sum, product, difference, and quotient of the two numbers.

Our input will look similar to that shown below, and we'll use this example to execute a test case against each of the Lambdas we create:

{
   "Number1": 10,
   "Number2": 20
}

We’ll be looking to receive the following in response:

{
   "Number1": 10,
   "Number2": 20,
   "Sum": 30,
   "Product": 200,
   "Difference": 10,
   "Quotient": 0.5
}

The following examples assume that you have an account with AWS. If you don’t have one, you can sign up for a free trial which will allow you to experiment with each of the examples below.

Writing Your Lambda with Python

Since Python is a scripting language, you can create the script directly within the AWS console. Log in to your AWS Account, and navigate to the Lambda console. Click on Create function. We’ll be creating a Lambda from scratch, so select the Author from scratch option.

Enter an appropriate name for your Lambda function, select a Python runtime and define a role for your Lambda to use. Since we won’t be using any external resources, we don’t need special permissions, but this is where you would add a role with those permissions.

Once everything is set, click on the Create function button.

Image title

Let’s take a TDD approach to this. We’ll start by setting up a new test event. Click on the Select a test event drop-down and choose Configure test events.

Image title

Amazon provides a significant collection of test templates. We’ll modify the Hello World template with data of our own. We’ll add a new event name and then click on Create to create the new test event.

 Creating a New Test Event

Once the test is created, we can trigger it with the Test button. The result is a successful execution, but we’re looking for a response other than “Hello from Lambda.” Let’s add some code to the Lambda to accomplish what we want. You can use the code below or use your python-foo to create something more elegant.


from __future__ import division

def lambda_handler(event, context):
   number1 = event['Number1']
   number2 = event['Number2']
   sum = number1 + number2
   product = number1 * number2
   difference = abs(number1 - number2)
   quotient = number1 / number2
   return {
       "Number1": number1,
       "Number2": number2,
       "Sum": sum,
       "Product": product,
       "Difference": difference,
       "Quotient": quotient
   }


Once you’ve entered the code, click on Save, and then click on the Test button to try it out. You should see a successful result like the one shown below:

 Fig. 4 Successful Python Lambda Execution

Let’s see if we can duplicate this effort with Node.js instead of Python.

Writing Your Lambda with Node.js

Navigate back to the Lambda console, and click on the Functions page. Click on Create function. As before, we’ll be creating a Lambda from scratch, so select the Author from scratch option. Enter a new name, select a Node.js Runtime, and we can reuse the role we created for the Python-based Lambda.

 Fig. 5 Creating a Node-based Lambda

We’ll use the same TDD approach for this Lambda, so we’ll start with creating a new test event. Follow the steps outlined above in the Python section. Once the test is created and you’ve triggered it to receive the standard “Hello from Lambda” result, we can add some code to get the expected response. The code below should calculate and return the required values:


exports.handler = (event, context, callback) => {
   var number1 = event.Number1;
   var number2 = event.Number2;
   var sum = number1 + number2;
   var product = number1 * number2;
   var difference = Math.abs(number1 - number2);
   var quotient = number1 / number2;
   callback(null, {
       "Number1": number1,
       "Number2": number2,
       "Sum": sum,
       "Product": product,
       "Difference": difference,
       "Quotient": quotient
   });
};


Anytime you make a change to the code, you’ll need to ensure you click on Save. If we click the Test button for the Lambda built using the code below, you should see a result similar to what is shown below:

 Successful Python Lambda Execution

Node.js and Python are both scripting languages, so we can enter the code directly in the AWS console. Java is a little different, so while the test case approach will be the same with both of the examples above, we’re going to need to package our Lambda into a JAR and upload it to the console.

Writing Your Lambda with Java

The first thing we’re going to do is create a fat JAR of our Lambda code. You can download the code for this example from this GitHub repository and build it by running the following command from the root folder of the project.


$ ./gradlew clean build shadowJar


When those tasks complete, you’ll have a JAR file in the build/libs directory of your project. Once you have the JAR, we can go about creating the Lambda and uploading the JAR.

Similar to the examples above, we’ll begin by navigating back to the Lambda console and selecting the Functions page. Click on Create function. Ensure you’re creating a Lambda from scratch by selecting the Author from scratch option. Enter a new name, select the Java 8 Runtime, and we can reuse the role we created for the Python-based Lambda.

 Creating a Java-based Lambda

Once we’ve created the Lambda, we need to upload the JAR to it. Select Upload a .ZIP or JAR file from the Code entry type drop-down, and then click on Upload. Navigate to the build/libs directory of your project and select the created JAR. You’ll have two files to choose from. Ensure you select the file with -all.jar at the end of the filename.

The next step is to configure the handler.  This is the package and class name of the Handler function, combined with the name of the primary handler function. If you’re using the example project, the handler is com.echovue.myFirstLambda.MyFirstLambda::handleRequest

Once you have the JAR selected and the handler configured, click on the Save button to upload and finish creating your Java Lambda. We can use the same test approach as we used from both the examples above, so scroll back up the Python section and create a test for the Lambda. Once you click on the Test button, you should see a result similar to the one shown below.

 Successful Java Lambda Invocation

Invoking Your Lambda Functions

As I mentioned back in the beginning, there are a plethora of ways to invoke Lambda functions: from S3 events, to Alexa triggers, to on demand triggers using AWS SDKs. For more information, I recommend checking out Amazon excellent documentation on how to do this.

 

 

 

 

Top