Reading Data From One Lambda Function From Another
In this article, I am going to explain how to create an AWS Lambda function and then call this role from another Lambda part within the same region. This is a useful scenario in which nosotros may need to execute a second lambda function based on the outcome of some previous logic. Another scenario may be to execute a 2d lambda function several times past using unlike parameters.
For the sake of this article, we volition consider a typical retailer application, in which we can buy different products from a retailer site using a lambda function.
Figure i – Architecture Diagram
If you consider the above architecture diagram, yous can run into that nosotros take an AWS lambda function – the ParentFunction, which assumes a specific role from the IAM (Invoke Other Lambda Function) and then calls some other lambda function – the ChildFunction with a payload. One time 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.
Equally in this example, let united states 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, summate the full sales corporeality, generate a transaction reference ID, and render this data to the ParentFunction.
Creating the beginning AWS Lambda Role – ChildFunction
Let united states commencement 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 lot are inside the panel, start searching for "Lambda" and click on the first upshot that appears from the drop-downward.
Effigy two – Search AWS Lambda Office
This will take you to the Lambda Function homepage, where you can create a new lambda role by hitting the "Create Role" push button.
Figure 3 – Create the AWS Lambda Function
Allow the name of this part be – "ChildFunction" and select Python iii.8 as the runtime.
Figure four – Function Proper name
Select the option to Create a new office with basic lambda permissions and click on Create Part.
Effigy v – Selecting the Role
A new lambda office will exist created where you can write your lawmaking and test information technology.
Figure half-dozen -AWS Lambda Function Created
Let united states of america at present caput over to Visual Studio Lawmaking 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 organisation information
- Return the upshot to the Parent Function
Figure 7 – Child Function Lawmaking
| one 2 3 4 five half-dozen 7 viii nine 10 eleven 12 13 14 15 xvi 17 18 nineteen 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import json import uuid def lambda_handler ( event , context ) : #one Read the input parameters productName = event [ 'ProductName' ] quantity = event [ 'Quantity' ] unitPrice = result [ 'UnitPrice' ] #ii Generate the Lodge Transaction ID transactionId = str ( uuid . uuid1 ( ) ) #3 Implement Business organization Logic amount = quantity * unitPrice #iv Format and return the result render { 'TransactionID' : transactionId , 'ProductName' : productName , 'Amount' : amount } ######################################################################### # No need to include the following snippet into the lambda role # Only used to examination the part locally event = { "ProductName" : "iPhone SE" , "Quantity" : ii , "UnitPrice" : 499 } response = lambda_handler ( issue , '' ) print ( response ) ######################################################################### |
One time the code is written and tested in the local machine, you can re-create and paste the script to the lambda function to test it in AWS.
Figure viii – Copying code to Lambda Function
In society to examination the ChildFunction, yous need to create the Test Event, in which you can laissez passer the payload data that we volition be using to call from the ParentFunction. In order to configure test events, click on Examination Consequence, and select Configure.
Figure 9 – Configure Exam Effect
Give the examination issue a proper noun and specify the payload information here to test it.
Figure 10 – Configure Test Event
Hit on Examination to execute the ChildFunction with the payload data.
Effigy 11 – Testing the Role
If the execution is successful, you volition get a successful return with the calculations completed as follows. As you can run across in the figure below, the function returns the following items.
- Transaction ID
- Production Name
- Corporeality
This information will also be visible to the ParentFunction when it calls the ChildFunction.
Figure 12 – Child Role Executed
Likewise, re-create the ARN of the Child Part, which tin exist used after to apply for policies and roles upon.
Effigy 13 – Copy ARN
Setting up the Policy for ParentFunction
In club to allow the ParentFunction to call the ChildFunction, nosotros need to provide the ParentFunction with specific rights to call some other lambda office. This tin can be washed past adding specific policies to a part and then assign that role to the lambda role.
Head over to the IAM module within the AWS portal and select Policies. Click on Create Policy to create a new 1.
Figure 14 – Create Policy
In the Create Policy page, select the JSON tab and add the following policy summary to it equally follows. Recollect to update the URL for the Resources which y'all have copied in the previous step. Give the policy a suitable name and create it. I am going to name this policy equally – "InvokeOtherLambdaPolicy".
Figure fifteen – Adding Policy JSON
Navigate to the Roles and click on Create role.
Figure 16 – Create Role
Select Lambda as the use instance and click on Side by side to add together the required permissions.
Figure 17 – Cull Utilise Case
Add the post-obit two policies to this role and create the role.
- AWSLambdaBasicExecutionRole
- InvokeOtherLambdaPolicy
Figure eighteen – Adding AWS Lambda Basic Execution Role
Figure 19 – Adding Invoke Other Lambda Policy
Click on Side by side and proceed forward and create the role. Give this role a suitable name, for instance, "InvokeOtherLambdaRole".
Creating the AWS Lambda Role – ParentFunction
Head over to the Lambda Function page and click on Create New Lambda function. I am calling this lambda part – "ParentFunction". Choose the run fourth dimension as Python 3.viii and assign the InvokeOtherLambdaRole role that we just created in the previous step.
Figure 20 – Creating the Parent Function
Let united states at present again caput over to Visual Studio Code to write the lawmaking and so copy-paste it dorsum to the lambda editor. Since we are going to use an AWS resources in this office, we demand to employ the Boto3 python library to use the AWS resource. This library tin can exist used to interact with other AWS resources as and when required.
Figure 21 – Code for the Parent Function
| 1 ii three 4 v 6 7 8 9 ten 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import json import boto3 # Ascertain the client to interact with AWS Lambda client = boto3 . client ( 'lambda' ) def lambda_handler ( event , context ) : # Ascertain the input parameters that will exist 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' ] ) impress ( '\n' ) print ( responseFromChild ) |
As you can see in the higher up code, we have created a boto client to interact with the lambda part. Also, we have created a payload that tin exist passed on to the ChildFunction when calling it. And once the ChildFunction is executed, it volition return the response, which will be stored in the "response" variable.
Finally, we can parse the payload data from the response and utilise it according to our needs. In this case, we are only going to print it on the screen. Re-create the lawmaking from VS Code to the lambda editor.
Effigy 22 – Parent Office
Create a sample test consequence for this function since we are not going to pass whatever payload for this Parent Function here. Save the event and click on the Test.
Figure 23 – Configuring Test Effect
Once you execute the ParentFunction, it will pass the payload information to the ChildFunction, where the upshot will exist calculated, and and so the terminal response will exist sent back from the ChildFunction to the ParentFunction. You lot can see the execution logs and confirm this as follows.
Figure 24 – Parent Function Executed
Determination
In this article, I have explained how we can call or execute an AWS Lambda function from another lambda function inside the aforementioned region. Using the AWS Lambda part, you can easily write serverless applications without having to worry near the infrastructure running behind information technology. Oft, it becomes necessary that nosotros might demand to telephone call different AWS Lambda functions from within another lambda due to the handling of complex business logic or something like that.
- Author
- Recent Posts
Source: https://www.sqlshack.com/calling-an-aws-lambda-function-from-another-lambda-function/
0 Response to "Reading Data From One Lambda Function From Another"
Post a Comment