In this article, I am going to explain how to create an AWS Lambda function and then call this function from another Lambda function within the same region. This is a useful scenario in which we may need to execute a second lambda function based on the outcome of some previous logic. Another scenario may be to execute a second lambda function several times by using different parameters.
For the sake of this article, we will consider a typical retailer application, in which we can purchase different products from a retailer site using a lambda function.
Figure 1 – Architecture Diagram
If you consider the above architecture diagram, you can see that we have an AWS lambda function – the ParentFunction, which assumes a specific role from the IAM (Invoke Other Lambda Function) and then calls another lambda function – the ChildFunction with a payload. Once the execution of the ChildFunction is completed, it returns a response, which is then passed on to the ParentFunction. The ParentFunction receives the response and handles the job accordingly.
As in this example, let us assume that the ParentFunction is going to call the ChildFunction with a payload of ProductName, Quantity, and the UnitPrice of that product. The ChildFunction, in turn, will process this payload, calculate the total sales amount, generate a transaction reference ID, and return this information to the ParentFunction.
Creating the first AWS Lambda Function – ChildFunction
Let us first go ahead and create the ChildFunction, which will process the input payload and return the results to the ParentFunction.
Head over to https://console.aws.amazon.com/ and login with your credentials. Once you are inside the console, start searching for “Lambda” and click on the first result that appears from the drop-down.
Figure 2 – Search AWS Lambda Function
This will take you to the Lambda Function homepage, where you can create a new lambda function by hitting the “Create Function” button.
Figure 3 – Create the AWS Lambda Function
Let the name of this function be – “ChildFunction” and select Python 3.8 as the runtime.
Figure 4 – Function Name
Select the option to Create a new role with basic lambda permissions and click on Create Function.
Figure 5 – Selecting the Role
A new lambda function will be created where you can write your code and test it.
Figure 6 -AWS Lambda Function Created
Let us now head over to Visual Studio Code and start writing our code for the ChildFunction as follows. This is a very simple application that is going to perform the following steps:
- Read data from the ParentFunction
- Generate the Transaction Reference ID
- Calculate the business information
- Return the result to the Parent Function
Figure 7 – Child Function Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import json import uuid def lambda_handler(event, context): #1 Read the input parameters productName = event['ProductName'] quantity = event['Quantity'] unitPrice = event['UnitPrice'] #2 Generate the Order Transaction ID transactionId = str(uuid.uuid1()) #3 Implement Business Logic amount = quantity * unitPrice #4 Format and return the result return { 'TransactionID' : transactionId, 'ProductName' : productName, 'Amount' : amount } ######################################################################### # No need to include the following snippet into the lambda function # Only used to test the function locally event = { "ProductName" : "iPhone SE", "Quantity" : 2, "UnitPrice" : 499 } response = lambda_handler(event,'') print(response) ######################################################################### |
Once the code is written and tested in the local machine, you can copy and paste the script to the lambda function to test it in AWS.
Figure 8 – Copying code to Lambda Function
In order to test the ChildFunction, you need to create the Test Event, in which you can pass the payload information that we will be using to call from the ParentFunction. In order to configure test events, click on Test Event, and select Configure.
Figure 9 – Configure Test Event
Give the test event a name and specify the payload information here to test it.
Figure 10 – Configure Test Event
Hit on Test to execute the ChildFunction with the payload information.
Figure 11 – Testing the Function
If the execution is successful, you will get a successful return with the calculations completed as follows. As you can see in the figure below, the function returns the following items.
- Transaction ID
- Product Name
- Amount
This information will also be visible to the ParentFunction when it calls the ChildFunction.
Figure 12 – Child Function Executed
Also, copy the ARN of the Child Function, which can be used later to apply for policies and roles upon.
Figure 13 – Copy ARN
Setting up the Policy for ParentFunction
In order to allow the ParentFunction to call the ChildFunction, we need to provide the ParentFunction with specific rights to call another lambda function. This can be done by adding specific policies to a role and then assign that role to the lambda function.
Head over to the IAM module inside the AWS portal and select Policies. Click on Create Policy to create a new one.
Figure 14 – Create Policy
In the Create Policy page, select the JSON tab and add the following policy summary to it as follows. Remember to update the URL for the Resource which you have copied in the previous step. Give the policy a suitable name and create it. I am going to name this policy as – “InvokeOtherLambdaPolicy”.
Figure 15 – Adding Policy JSON
Navigate to the Roles and click on Create role.
Figure 16 – Create Role
Select Lambda as the use case and click on Next to add the required permissions.
Figure 17 – Choose Use Case
Add the following two policies to this role and create the role.
- AWSLambdaBasicExecutionRole
- InvokeOtherLambdaPolicy
Figure 18 – Adding AWS Lambda Basic Execution Role
Figure 19 – Adding Invoke Other Lambda Policy
Click on Next and proceed forward and create the role. Give this role a suitable name, for example, “InvokeOtherLambdaRole”.
Creating the AWS Lambda Function – ParentFunction
Head over to the Lambda Function page and click on Create New Lambda function. I am calling this lambda function – “ParentFunction”. Choose the run time as Python 3.8 and assign the InvokeOtherLambdaRole role that we just created in the previous step.
Figure 20 – Creating the Parent Function
Let us now again head over to Visual Studio Code to write the code and then copy-paste it back to the lambda editor. Since we are going to use an AWS resource in this function, we need to use the Boto3 python library to use the AWS resources. This library can be used to interact with other AWS resources as and when required.
Figure 21 – Code for the Parent Function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import json import boto3 # Define the client to interact with AWS Lambda client = boto3.client('lambda') def lambda_handler(event,context): # Define the input parameters that will be passed # on to the child function inputParams = { "ProductName" : "iPhone SE", "Quantity" : 2, "UnitPrice" : 499 } response = client.invoke( FunctionName = 'arn:aws:lambda:eu-west-1:890277245818:function:ChildFunction', InvocationType = 'RequestResponse', Payload = json.dumps(inputParams) ) responseFromChild = json.load(response['Payload']) print('\n') print(responseFromChild) |
As you can see in the above code, we have created a boto client to interact with the lambda function. Also, we have created a payload that can be passed on to the ChildFunction when calling it. And once the ChildFunction is executed, it will return the response, which will be stored in the “response” variable.
Finally, we can parse the payload information from the response and use it according to our needs. In this case, we are just going to print it on the screen. Copy the code from VS Code to the lambda editor.
Figure 22 – Parent Function
Create a sample test event for this function since we are not going to pass any payload for this Parent Function here. Save the event and click on the Test.
Figure 23 – Configuring Test Event
Once you execute the ParentFunction, it will pass the payload information to the ChildFunction, where the result will be calculated, and then the final response will be sent back from the ChildFunction to the ParentFunction. You can see the execution logs and confirm this as follows.
Figure 24 – Parent Function Executed
Conclusion
In this article, I have explained how we can call or execute an AWS Lambda function from another lambda function within the same region. Using the AWS Lambda function, you can easily write serverless applications without having to worry about the infrastructure running behind it. Often, it becomes necessary that we might need to call different AWS Lambda functions from within another lambda due to the handling of complex business logic or something like that.
- Getting started with PostgreSQL on Docker - August 12, 2022
- Getting started with Spatial Data in PostgreSQL - January 13, 2022
- An overview of Power BI Incremental Refresh - December 6, 2021