How to call AWS Lambda Function from another AWS Lambda Function in Python

In this example Python code, we will show you how to invoke AWS Lambda function from another AWS Lambda function:

We can use AWS Lambda to add custom logic to other AWS services or build our own backend services. AWS Lambda is a serverless compute service. It automatically manages the underlying compute resources while running your code in response to events.

AWS Lambda automatically executes code in response to a variety of events, including HTTP requests via Amazon API Gateway, object modifications in Amazon Simple Storage Service (Amazon S3) buckets, Amazon DynamoDB table updates, and AWS Step Function state transitions.

Note: The second AWS Lambda must have permission to called the first AWS Lambda.

Let MyCalculatorLambda be the name of our first AWS Lambda with the following code:


def lambda_handler(event, context):
    numbers_data = event['numbers_data']
    print(numbers_data)
    first_num = numbers_data[0]
    second_num =  numbers_data[1]
    result = first_num * second_num
    return result

Now, to call the first AWS Lambda's function from the second AWS Lambda, write the following code in the second AWS Lambda function:


import boto3
import botocore
import json

#Name of the AWS Lamda to invoke
CALCULATOR_LAMBDA_NAME = "MyCalculatorLambda"

config = botocore.Config(read_timeout=5000,
                         connect_timeout=300,
                         retries={"max_attempts": 4})

session = boto3.Session()
lambda_client = session.client('lambda', config=config)


def lambda_handler(event, context):
    # call first lambda
    numbers_data = [10, 45]
    try:
        response = lambda_client.invoke(FunctionName=CALCULATOR_LAMBDA_NAME,
                                        InvocationType='RequestResponse',
                                        Payload=json.dumps(numbers_data))
        res_str = response['Payload'].read()
        if res_str:
            res_data = json.loads(res_str)
            print("Result data : ", res_data)
        else:
            print("No Empty")
    except Exception as ex:
        print("Error :", ex)

The running of the second Lambda function will give the following output:

Result data : 450