Serverless Future: Creating your first AWS Lambda function

Howdy techies! I’m Tanmay with the DevOps team at Ecomm India Cloud IT which helps companies with cloud transformation and DevOps processes on top of cloud Platforms like AWS. Part of what I do everyday is help organizations drastically increase their pace of innovation by removing bottlenecks with DevOps pipelines that increase their performance efficiency and reduce cost.

I have been working on few exciting projects in the recent months involving Rest API’s and Serverless architecture. I thought I would share with you some of the serverless tools and techniques that i have learnt which might help you with your future projects.

So, in this article I will be showing you how to create a serverless function and a rest api to trigger this serverless function. For this I will be using Amazon Web Services Lambda and API Gateway. I will be creating a basic Even Odd Function using python environment, where the function will determine whether the user input is even or odd. I am selecting a very basic function, so that anybody can use this article to start learning Lambda function and API gateway without needing too much coding experience. However, it is recommended that the user should know basics of AWS. If you are new to cloud computing and want to make a career in it, I recommend you to visit AWS training section on our website for more hands-on training on AWS.

So, what is serverless computing?

About a decade ago or physical servers were still in demand, thanks to cloud servers that is no longer the case, technically the physical servers still do exist it’s just that you don’t need to manage them as they are either automated or managed by a service provider at a very low cost. And now serverless is abstracting cloud servers.

Serverless architecture is defined by stateless compute containers and modeled for an event-driven solution. AWS Lambda is the perfect example of serverless architecture and employs Functions as a service (FaaS) model of cloud computing. Platform as a Service (PaaS) architectures popularized by Salesforce Heroku, AWS Elastic Beanstalk and Microsoft Azure simplify applications deployment for developers. And serverless architecture or FaaS is the next step in that direction.

Advantage of going serverless

Main advantage is that you no longer need to keep a cloud server / instance running all the time. The serverless compute capacity appears when you need it, then disappears when you’re done with it just like a function and all your business logic can now live within these functions.

So, what can you do with Lambda Functions?

You can do a simple echo function, to a fully operational automated chatbot for your website, possibilities are endless.

Before we get our hands dirty here are few things that you require to create your first lambda function:

  1. 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.
  2. Basic understanding of programming environment, AWS Lambda currently supports code written in js (JavaScript), Python, Java (Java 8 compatible), and C# (.NET Core). Your code can include existing libraries, even native ones. Please read AWS documentation on using Node.js, Python, Java, and C#.

Once you are done with setting up your AWS Account we can move on to creating our even odd function in python 2.7 environment using AWS Lambda and API gateway.

Getting Started

Right, now that we have the basic things in order, we can dig in! To get started, login to your AWS Management console, once done you should see a screen like below:

Make a note of the region you are working in, as all your resources will be created in this region. I’m using “US-East-2” region that is “Ohio”. Click here or more information on regions and availability zones.

AWS Lambda Function

To start with the coding click on the Lambda link present under Compute section or just write in the text bar provided below AWS Services title. For this post, I am creating a function which will check whether the given number is even or odd.

You should see below page if you have never used AWS Lambda before, from here you can quickly access documentation related to Lambda, find out its cost or could learn new features. Take your time to go through these details before proceeding to create a function.

Blueprint

Once you are ready click on the create a function on the top right corner of this page.

You can see some sample blueprints on this screen to start off with or can start from scratch, for this blog I will start from scratch.

After you click author from scratch you should get below screen.

Triggers

Here you can configure the triggers which will call this Lambda function and give you the result depending on the code, you can choose from a few options.  I will be using API Gateway as the trigger method, this way we can test the Lambda function from our browser. So, update the values as shown below. Please note for simplicity reasons I am keeping the security open, it is recommended that you use either AWS IAM or Access ID & Code for securing your API from other users. That is advanced method and we shall cover that later. Once you are done with making changes to your screen click next.

Configure Function

After this click next, you should get below screen.

Change the runtime environment from Node.js 6.10 to Python 2.7 as I am providing the code in python language. Make sure you give an appropriate Name to the function and an optional description.  I have updated the Name and Description of the function to indicate its purpose.

Once you are done, scroll down to start with your code.

Code

def lambda_handler(event, context):

    #We are accepting a number from the user and storing it in variable num.

            num = event['number']

            #The % operator is the modulo, which returns the remainder rather than the quotient after division.

            res = num % 2

            if res == 0:

                #Check whether the remainder is 0 if so set the return message to even.

                        ret = "%d Number is an even number!" %(num)

            else:

                #set the return message to odd.

                        ret = "%d Number is an odd number!" %(num)

            return ret

Handler & Permissions

Once you are done writing the code make sure you set the handler name with function.lambda_handler where function is the name of your function, for me its evenodd hence my handler is evenodd.lambda_handler. Next step is to create a role to allow this lambda to execute the function, select an appropriate name for the role and attach policy template by typing lambda inside the dropdown box indicated by the arrow, you should select “Basic Edge Lambda Permissions”

Scroll down and click on advanced settings and edit the time out from 3 seconds to 30 seconds.

Leave all other things to default. After that click, next and you should see below screen:

Finally click on the create function button.

Testing

Next step is to click on Test button, edit the test document as shown below:

And click save and test. You should see a window similar to below window:

If you get execution result as succeeded then that means our function is working as expected.

We have tested the function from within the lambda function for complete functionality we have a trigger to invoke this lambda function from outside of the AWS. But first we need to update a few things in our API gateway.

API Gateway

Click on API Gateway it is in the Application Services section, or you can write API Gateway in the text bar at the top. Once you open API Gateway you should get below screen:

You can see that the lambda function has already created an API for us as we defined it in the trigger section declaration of lambda function. So, click on this API to get started.

Create Methods

Click on the resource (/evenodd) to see below screen

By default, when you create a trigger of API Gateway from Lambda function it creates the any method for its execution. However, I am going to create a new method to use this API gateway. First, I will create a Get method and later I will create a POST method. To start this process, click on the action button at the top and select create method

GET Method

Select GET Method from the dropdown list.

In here use the integration type as Lambda function and then select the Lambda region that you have used to create your lambda in, for me it was US-EAST-2 (Ohio) so my settings are like:

 

Once you are done with updating the details, click next and you’d get a pop up like below.

click ok on this message to get a screen like below.

Now click on the Integration Request link highlighted in the below image:

Integration Request

You should get a screen like:

Now click on the arrow next to “Body Mapping Templates”

 

Body Mapping Templates

By default, there are no templates defined, so select second option on “Request Body Passthrough” that is when there are no templates defined (Recommended) option and click on add mapping templates.

You should get a box like below:

By default, the content-type suggested is application/json but it is greyed out so you will need to type it in that box and click on the tick next to it. Once done write in the template section as shown in the below snapshot, and click save. Template field contains:

{"number" : $input.params('number')}

Deployment

Once done click on the actions button at the top and select deploy API to get below screen:

You can select a new stage or select an existing stage to overwrite it. I am overwriting the Prod stage, once done click deploy.

Once you click deploy you should be redirected to the stages click on the stage to expand it:

Select the method that was created (Get), copy the invoke URL path and add “?number=20” to it and paste it in a new browser window.

https://n79ttbsqyf.execute-api.us-east-2.amazonaws.com/prod/evenodd?number=20

*** replace above link with your link and use this endpoint. ***

Similarly, you can change the value of the number in the above link and you can check any number.

https://n79ttbsqyf.execute-api.us-east-2.amazonaws.com/prod/evenodd?number=11

*** replace above link with your link and use this endpoint. ***

This way we know that our function can be called using the Get method.

POST Method

We can also use the POST method to invoke our function. To create the post method go back to API Gateway Console. Select the API, click on resources and expand the methods. Once you do that you should get below window:

Click on Actions button and select create method and select POST method from the dropdown list. And update the details like we did for the Get method. Once done hit save and you will get a pop like below.

 

Click ok on this pop up message.

Integration Request

Once you click ok you should get a screen like below:

We will be repeating steps that we did in the Get method.

 

Body mapping templates

Now click on the Integration Request link that you see. Scroll down after you have clicked till you find Body mapping templates.

By default, there is no body mapping template defined, this template is used to parse the response that you get from Lambda function to a user readable format, without this the API Gateway will not be able to reproduce the response of the lambda function.

So, click on the add mapping template and select below options:

By default, the content-type suggested is application/json but it is greyed out so you will need to type it in that box and click on the tick next to it. Once done write in the template section as shown in the below snapshot, and click save. Template field contains: {“number” : $input.params(‘number’)}

Once done click save.

Click on “Method Execution” button to go back to the POST method page.

Integration Response

Now click on “Integration Response” link

You should see a screen like below, click on the highlighted arrow.

You should get a screen like below, click on the highlighted part.

And select “Convert to text (if needed)” from the dropdown list and hit save.

Once done click on Actions button, click on Deploy API option.

Deployment

Select a new stage and deploy the API.

You can notice the newly created stage in the stages options. Select the newly created stage, select POST method and copy the invoke URL as highlighted below.

Copy the invoke URL that you see and you can use it directly to invoke the Lambda function via this stage and method of the API. Now open your browser paste invoke URL and add “?number=20” and press enter. (Note you can change this number to any integer value.)

 https://n79ttbsqyf.execute-api.us-east-2.amazonaws.com/post/evenodd?number=20

*** replace above link with your link and use this endpoint. ***

Congratulations -  you have just set up and deployed your own Lambda Function & API Gateway!

Deleting Resources

To delete these resources, follow below screenshots:

API Gateway

To delete the API, go back to the API Gateway page and select the API Gateway, then click on the actions button and select “Delete API” option.

Once you click on the Delete API you will get below pop up type the name of the API in the text box and then click delete API, make sure you type correct name otherwise you may delete any other resources.

Lambda Function

Similarly, to delete the Lambda function, go to Lambda console, and select the function to delete it.

Click the delete button at the top, below pop up will follow:

Confirm delete by clicking on Delete, this way the function gets deleted.

Congratulations you have successfully completed this simple AWS Lambda Function.

If you have any questions related to this post or face any problems, then do comment and I will try to resolve them as quickly as possible.

Thanks for reading!

Subscribe to our newsletter: