Bootstrap FreeKB - Amazon Web Services (AWS) - Invoke Lambda Function using Python boto3
Amazon Web Services (AWS) - Invoke Lambda Function using Python boto3


This assumes you are familar with the basic configurations needed to connect to Amazon Web Services (AWS) using Python boto3. If not, check out my article Python (Scripting) - Getting Started with Amazon Web Services (AWS) boto3.

Here is the minimal boilerplate code without any error handling to invoke the Lambda Function named "my-lambda-function".

#!/usr/bin/python3
import boto3

client = boto3.client('lambda')
response = client.invoke(
        FunctionName="my-lambda-function"
        )

print(response)

 

Here is a more practical example, with try/except/else error handling.

#!/usr/bin/python3
import boto3
import sys

try:
  client = boto3.client('lambda')
except Exception as exception:
  print(exception)
  sys.exit(1)

try:
  response = client.invoke(
        FunctionName="my-lambda-function"
        )
except Exception as exception:
  print(exception)
else:
  print(f"response = {response}")

 

Which should return something like this.

{
  'ResponseMetadata': {
    'RequestId': '68560a0e-df18-4ed0-9241-fea5b6932a07', 
    'HTTPStatusCode': 200, 
    'HTTPHeaders': {
      'date': 'Sat, 27 Apr 2024 05:16:46 GMT', 
      'content-type': 'application/json', 
      'content-length': '53', 
      'connection': 'keep-alive', 
      'x-amzn-requestid': '68560a0e-df18-4ed0-9241-fea5b6932a07', 
      'x-amzn-remapped-content-length': '0', 
      'x-amz-executed-version': '$LATEST', 
      'x-amzn-trace-id': 'root=1-662c8a3e-700ece1869e8ebf66b3434cc;parent=6662bc5c53ab48f1;sampled=0;lineage=458c89d0:0'
    }, 
    'RetryAttempts': 0
  }, 
  'StatusCode': 200, 
  'ExecutedVersion': '$LATEST', 
  'Payload': <botocore.response.StreamingBody object at 0x7f6deb2e5f40>
}

 

Notice in this example that the response has 'Payload': <botocore.response.StreamingBody object at 0x7f6deb2e5f40>. Here is one way to parse the payload.

print(response['Payload'].read().decode('utf-8'))

 

Which should then return something like this.

{"statusCode": 200, "body": "\"Hello from Lambda!\""}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 95a2c6 in the box below so that we can be sure you are a human.