Cook a recipe with AWS: Simple and Easy Lambda Functions
Tags: webdev, beginners, programming, python
Published: 2022-12-09 18:42:42




![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ceqkba78v11o8gb87e8n.png)



## AWS Lambda
**AWS Lambda** is a **compute service**. **You can use it to run code without provisioning or managing servers.** 

> ## Lambda function
> **The code you run on AWS Lambda is called a Lambda function**
> **Lambda functions** lack any ties to the underlying infrastructure and are **stateless**

> Lambda supports the following languages:
> - Node.js
> - Python
> - Java
> - Go
> - C#
> - Ruby
> - PowerShell

Lets get started with AWS Lambda and cook some easy Lambda functions using Python


## Ingredient
- Python

## Prerequisites
- Log into AWS account with a valid user credentials
(Root user not preferred)

**Lets Jump to the Recipe**

##Author Lambda Functions in Python

<u>Steps to create</u>


- Open the Lambda from the aws console

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ty3qvospemwf2f2wc412.png)


- Click **Create Function** button

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ttzus47hr5vwtvy9mgfq.png)


- Choose **Author from scratch option**
-Specify a Function name, I am going to create a function to print a Welcome message to the user. So my function name is going to be "Welcome_user" 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u7xcu9uox1yj2nlyyvf0.png)


- Choose **Python** <latest version> as your runtime. For me its Python 3.9 now and I am selecting it

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0vtqqiqe60l3aow1y3i6.png)


- Scroll down and now leave the rest of the settings to the **default selections**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1kzkm6x1wkcno2zz6ysl.png)



> By **default**, Lambda will create an execution role with permissions to upload logs to Amazon CloudWatch Logs

> An **IAM execution role** defines the **permissions that control what the function is allowed to do when interacting with other AWS services.**
- **Create a new role with basic Lambda permissions** will be **selected by default**

- Now I will be able to see the following message
"Lambda will create an execution role named Welcome_user-role-<xxx>, with permission to upload logs to Amazon CloudWatch Logs"
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z8cs6vxijsnu33msp4h9.png)


- Scroll down and Click **Create Function** button

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jd5ehjoawlk3su0vnbe.png)








- Lets wait for couple of minutes to get navigated to the function page

- Now on the function dashboard, there are several tabs Code, Test, Monitor, Configuration, Aliases, and Versions

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g38b66umdw85xexoyvte.png)


- We are now on the Code tab, down here we can see a lambda_function.py file.

Replace the code on the file with the below code 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/femsgoihkh6iqrp91frx.png)


```
import json

def lambda_handler(event, context):
    message = 'Welcome {} {} to Cloud Tuner,  Get cloudified with AWS'.format(event['first_name'], event['last_name'])  

    #print to CloudWatch logs
    print(message)

    return { 
        'message' : message
    }
```



> The above function will print the welcome message with your name which you would pass through json while testing the code. The message will be also printed to the cloud watch logs 

> The return statement will return the value in the message variable
 
<u>The Lambda function handler</u>

- The Lambda function handler is the method in your function code that processes events.
- The handler method takes two objects – the event object(mandatory parameter) and context object (optional parameter)
   - event object: An object with information about the event that initiated the Lambda function
   - context object: This is generated by AWS and provides metadata about the action

- Now **Deploy the function** by clicking on **Deploy** button

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qzidfy39d7uxzipkd0lj.png)



- You should be able to see **Changes Deployed** once deployment completed


Now we have successfully deployed our code. Now its the time to test the code 

##Create a Test Event and Execute the Lambda Function

> **A test event is a JSON object that mocks the structure of requests emitted by AWS services to invoke a Lambda function**. Use it to see the function’s invocation result.

<u>Steps to create</u>

- Click the arrow next to the button **Test**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o9o4g8jf3u4w6wy2ig9q.png)

- Click **Configure test event**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69xj9cqckt0l5f31vi8t.png)


- Lets create a new test event
- Specify the Event name, I am going to name as "Welcome_user_test_event"

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/be1p4wdsouqs6jd7n7ae.png)



- Replace the code on **Event JSON** with the below code 

`{
  "first_name": "Ruby",
  "last_name": "Jade"
}`


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8vn6czr00z478qgy6o7p.png)


- Click Format JSON button to get the JSON code formatted
- Now Click on **Save** button

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/htk4g23q0z68283n9anw.png)


- We have created the Test Event successfully
Lets Test the lambda code by clicking on the **Test** Button

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tedslash1h1oomjchj4d.png)


And  We can notice that execution results and the message getting printed "Welcome Ruby Jade to Cloud Tuner,  Get cloudified with AWS"

You can also see **Duration which is the execution time**
**Billed Duration is the time you are actually billed for**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zydz6bu6hs7nddb25ayc.png)

Before wrapping up, Remember, **Lambda functions are short lived; the Lambda max timeout is 900 seconds (15 minutes)**

Now, Lets verify if the CloudWatch has captured the Function Logs

##Check Cloud Watch for the Function logs

<u>Steps</u>

- Click on this **Monitor** tab.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j29sbuc1js9goe9ermge.png)


This shows high-level CloudWatch metrics about our function with the details about number of invocations, duration, error count and success rate
- To see detailed logs in Cloud Watch, Click **View Logs in Cloud Watch**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ae9u2vleb9s5a3kkcsuq.png)


- You will be navigated to cloud watch dashboard
- You will be able to see detailed logs in **Log stream**



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3pwjr7urro65ud2gfh3e.png)



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pb5ah4gln5owz368xzg5.png)

## Some additional recipes
Try cooking Variety of Lambda Functions by following the above steps.
Below are the recipe for four different Lambda function along with JSON code which can be used to create  Test Event to test them

## Lambda Function to calculate the Square Root of a number

Function Name: SquareRoot
**Function code**
```
import json
import math
def lambda_handler(event, context):
    #to convert string to integer
    input =int(event['number'])
    squareroot = math.sqrt(input)
    message = 'The square root of the number {} is  {}! '.format(event['number'],squareroot)  

    #print to CloudWatch logs
    print(message)

    return { 
        'message' : message
    }

```

**Event JSON code**
`{
  "number": 16
}
`

 

## Lambda Function to calculate length of your name 

Function Name: NameLength 

**Function code**
```
import json
def lambda_handler(event, context):
    input = event['name']
    length_of_your_name= len(input)

    #print to CloudWatch logs
    print(input)
    print(length_of_your_name)

    return { 
        'input' : input,
        'length_of_your_name':length_of_your_name
        
    }
```
**Event JSON code**
`{
  "name": "Tuner"
}
`

## Lambda Function to search a word on the input string 

Function Name: SearchString
**Function code**
```
import json

def lambda_handler(event, context):
    input=event['input_string']
    key=event['word_to_be_searched']
    isPresent=key in input
    message = 'The presence of  {} in  {} is {} '.format(key,input,isPresent)  

    #print to CloudWatch logs
    print(message)

    return { 
        'message' : message
    }
```
**Event JSON code**
`{
  "input_string": "Stay tuned with Cloud Tuner and get cloudified with AWS",
  "word_to_be_searched": "AWS"
}`

## Lambda Function to reverse the input string 

Function Name: ReverseString
**Function code**
```
import json

def lambda_handler(event, context):
    input= event['first_name']
    reversed_string = event['first_name'][::-1]
    print(reversed_string)
    #print to CloudWatch logs
  

    return { 
        'input':input,
        'reversed_string' : reversed_string
    }

```
**Event JSON code**
`{
  "first_name": "cloud"
}`

Thank You