Amazon Lambda - Hands On Demo

In this Lab, we will invoke an API configured through API Gateway.

API will in turn invoke the Lambda function, which will trigger an SNS Email Notification.

API Gateway

Lambda Function

Simple Notification Service (SNS)

Create a topic and a subscription for Email Notification

 

Please follow this tutorial first to create a SNS Topic and a Subscription first

Create a Lambda Function

 

  1. Paste the following code to create the Lambda function named "PythonHelloWorld".
  2. Runtime: Python 3.12
  3. Keep all others values as default.
import boto3

def lambda_handler(event, context):
    # Initialize SNS client
    sns = boto3.client('sns')

    # Specify your SNS topic ARN
    topic_arn = 'arn:aws:sns:us-east-1:211125437318:MyTopic'

    # Publish a message to the SNS topic
    sns.publish(
        TopicArn=topic_arn,
        Message='Hello from Lambda! This is the message that will be sent in the email.',
        Subject='Email Subject from Lambda'
    )

    return {
        'statusCode': 200,
        'body': 'Message published to SNS topic successfully!'
    }

Add an API Gateway Trigger

 

  1. Click "Add Trigger" and select "API Gateway".
  2. Select "Create a new API".
  3. API Type: HTTP API.
  4. Security: Open.
  5. API Name (default): PythonHelloWorld-API.
  6. Select "Cross-origin resource sharing (CORS)".
  7. Click Add.

Add a Destination

 

  1. Source: Asynchronous invocation
  2. Condition: On success
  3. Destination type: SNS topic
  4. Destination: arn:aws:sns:us-east-1:<ACCOUNT-ID>:MyTopic
  5. Permissions: Add required permissions

Test

 

  1. Open a new browser window.
  2. Paste the API URL like.
  3. Check Email.

Thanks

For

Watching