Creating and Deploying Python Code in AWS Lambda

In this blog, we are going to create an AWS Lambda function from scratch and deploy it. Since the complete code is written in Python, I assume that reader’s of this article have basic knowledge of Python programming.

What is AWS Lambda?

Lambda is a serverless compute service provided by Amazon Web Services(AWS). It allows us to run our code without worrying about how the server gets managed in the backend. Based on the frequency of request, AWS Lambda can automatically scale up or down as and when needed. Since we pay only for the compute time we consume, we should make sure that the code deployed in lambda is highly optimized. 

Before we proceed ahead, let’s get familiar with some of the technical jargon’s which we will be using in this article.

Events

An event is a JSON formatted document that contains data required by function to process. 

Eg: custom event – customer data

{
“name” : “Alen”,
“age” : 23,
“id” : 1
}

Lambda handler

Is a function which gets invoked by an event. This in return runs the code on AWS Lambda.

Trigger

Anything which invokes a lambda function, is called a trigger. For eg: we can trigger our lambda function using an SNS request, or, we can have an API Gateway to trigger our lambda function, or, our lambda function can feed in from SQS queue, etc.

I guess, this basic knowledge is good to get going. Now, let’s proceed ahead and create a lambda function.

For creating a lambda function, we need an IAM role which has full permission of Lambda.

Step 1)

Login to your AWS account, search for “IAM” and then click “Create role”.

Click “Next”

Now, we need to create a policy to provide required permission. AWS provides predefined policy for accessing Lambda.



Search for “AWSLambdaFullAccess” and click “next”.

At last, fill in the details like role name, description and then click “create role”

Step 2) 

Go back to AWS Management Console and search for “Lambda”

Next, choose “function” and then click on “create function”

Give the function name as shown above, and choose the language as “Python 3.6”. In the “Execution role” section, select “Use an existing role” and then search for the role which we had created in Step 1. Once selected, click “create function”.

If you have successfully completed all the steps, congrats, you have created your first AWS Lambda function. If not, I would suggest you to start from step-1 again.

Moving ahead, I have written a simple Python program to check if “age” is > 18 or not. Please go through the below code snippet and try to understand it.

The entry point for the lambda function named “testLambda” is, “lambda_handler”.

__author__ = ‘@Sumit Anand’
__copyright__ = “Copyright (C) Sumit Anand”
__version__ = ‘1.0’


def check_age_limit(data):

    if data[‘age’] < 18:
        print(“{0} is below 18. Cannot proceed”.format(data[‘name’]))

    else:
        print(“Congrats, you can proceed as you are {} years old “.format(data[‘age’]))


def lambda_handler(event, context):

    try:
        print(“Event is {} “.format(event))

        if ‘age’ in event and ‘name’ in event:

            check_age_limit(event)

            return {
                ‘statusCode’: 200,
                ‘Status’: ‘Request Received’
            }

        else:
            return {
                ‘statusCode’: 400,
                ‘Status’: ‘Bad Request’
            }

    except Exception as err:
        print(“Error in lambda_handler {}”.format(str(err)))

        return {
            ‘statusCode’: 500,
            ‘Status’: ‘Internal Server Error’
        }
A basic lambda handler

In your local environment, create a project folder named “testLambda” and then a python file named “lambda_main.py”. Inside this file, copy paste the above code snippet. Once done, create a zip of your project. This package (.zip) will be uploaded to the lambda function which we have created earlier.

Note: In the “handler” section, we have given the name of the file where we have defined our handler.

Syntax: <file_name>.<handler_function>
Eg: lambda_main.lambda_handler

Once the package is uploaded, click “save” . Just to verify, if everything went as mentioned or not, check the code section in your lambda function. You will see the same code which I have mentioned earlier.

Well, you have successfully deployed a Python code in AWS Lambda. It’s time to test whether everything is working fine or not. 

AWS provides a way to unit test the lambda code by creating events from the console as well. 

On the top right corner, select the drop down and click “configure test event”

As we need “name” and “age” in our events/request, create a template as shown below.
Note: Actual template will have different data, you need to edit as shown.

After this, click “create”. Once created, click on “test”.

Hurray, you have tested your first Lambda function. 

Just to make sure that our age check logic is correct, I had created another test event with age as 17 and triggered the lambda.

I hope you were able to create and deploy your first Python code in AWS Lambda. 

Happy Learning!

Published by Sumit Anand

I'm a data enthusiast, currently working as Data Engineer.

6 thoughts on “Creating and Deploying Python Code in AWS Lambda

  1. Nicely Explained, I have one doubt you are using `existing role` in Permissions. Is it default from AWS and if it is default then is it secure?

    Like

Leave a reply to Sumit Anand Cancel reply

Design a site like this with WordPress.com
Get started