Building Serverless Notification Automation with AWS Lambda and NOVU API

Building Serverless Notification Automation with AWS Lambda and NOVU API

Empower Your Lambda Functions for Automated Notifications

·

5 min read

In today's fast-paced digital landscape, automated notification is a vital component of engaging with users, clients, and customers. Harnessing the power of serverless computing and cloud services, businesses and developers can create efficient, scalable notification workflows that deliver timely and personalized messages. In this article, we'll explore the seamless integration of two robust technologies—AWS Lambda and the NOVU API—to develop a serverless email automation system. This article is not an introduction to AWS or AWS Lambda, in case you are new to AWS, start from here

What is Azure Speech

AWS Lambda is a powerful, serverless computing service offered by Amazon Web Services (AWS) that enables developers to run code in response to various events without the need to manage the underlying infrastructure. It allows you to execute functions in a highly scalable and cost-effective manner, automatically provisioning and scaling resources as needed.

What is Novu

NOVU is an open-source notification infrastructure designed to simplify the process of implementing rich product notification experiences for engineering teams. It offers a range of tools and components, including backend API clients for multiple programming languages, prebuilt components for in-app user notification feeds, integration with delivery providers, and a scalable, reliable infrastructure for high-volume notification delivery.

Let's Begin

Step 1 - Setting Up NOVU

  1. Head on to https://novu.co/

  2. Activate Email as Notification channel, this is being used for this article

  1. Create a New Workflow

  1. Create a Blank workflow

  1. Add Email as Notifier, and setup it

  1. Add Sender Name, Subject and under Custom Code add {{Results}} We will use this as key in our payload.

  1. Get API Key to use in Lambda

Step 2 - Setting Up AWS LAMBDA & S3

We are primarily using S3 just to invoke Lambda, S3 can be replaced with any service, and Email can be replaced with any notification type

  1. Create Bucket & Allow Public Access

  1. Create Lambda and add this Bucket as Trigger

  1. Add Environment Variables - NOVU_KEY , AWS_SECRET_KEY and AWS_ACCESS_KEY

Step 3 - Installing Libraries

  1. python3 -m venv venv

  2. source venv/bin/activate

  3. pip install boto3

Step 4 - Code

Libraries & Client

import boto3
import json
import os
import urllib3
import logging
import time
import uuid

# Initialize AWS clients using environment variables
aws_access_key_id = os.environ['AWS_ACCESS']
aws_secret_access_key = os.environ['AWS_SECRET']
aws_region = "us-east-1"
novu_key = os.environ['NOVU_KEY']

# Initialize AWS clients
s3 = boto3.client('s3', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=aws_region)

# Initialize logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

Functions

  1. Emailer Service
sender_email = "sender_email@gmail.com"
recipient_email = "recipient_email@gmail.com"

def send_mail(payload):
    """
    Send EMAIL with NOVU API
    :param payload:
    :return:
    """
    url = 'https://api.novu.co/v1/events/trigger'
    headers = {
        'Authorization': 'ApiKey ' + novu_key,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    data = {
        "name": "emailerworkflow",
        "to":{
            "subscriberId": str(uuid.uuid4()),
            "email": recipient_email
        },
        "payload": ({'Message': "Hi User !",'Results': json.dumps(payload)})
    }

    # Send the POST request
    http = urllib3.PoolManager()
    encoded_data = json.dumps(data).encode('utf-8')
    response = http.request('POST', url, headers=headers, body=encoded_data)

    return response
  • API Endpoint Configuration: In the first part of the function, it configures the URL for the NOVU API endpoint ('https://api.novu.co/v1/events/trigger'), which is the destination where the email request will be sent.

  • HTTP Request Headers: It defines the necessary HTTP request headers to ensure the request is properly formatted and authenticated.

    • 'Authorization': The API key (novu_key) is included in the 'ApiKey' format to authenticate the request.

    • 'Content-Type': The 'Content-Type' header specifies that the data in the request is in JSON format.

    • 'Accept': The 'Accept' header indicates that the response is expected in JSON format.

  • Constructing the JSON Payload: The function creates a JSON payload to send to the NOVU API. This payload typically consists of the following elements:

    • "name": A name for the email workflow, which is set to "email workflow."

    • "to": Information about the recipient, including a subscriber ID (generated using uuid.uuid4()) and the recipient's email address (recipient_email).

    • "payload": This section contains the actual email message, which includes a greeting message and any additional content passed in the payload parameter. It includes a 'Message' and 'Results' field.

  1. Lambda Handler
def lambda_handler(event, context):
    """
    Lambda handler
    :param event:
    :param context:
    :return:
    """
    try:
        bucket_name = 'helpernovubucket'
        print(event)
        send_mail(event)
        return {
            'statusCode': 200,
            'body': json.dumps('Email Sent')
        }
    except Exception as e:
        logger.error(e)
        return {
            'statusCode': 500,
            'body': json.dumps('Error')
        }
  • Function Purpose: The lambda_handler function is the main entry point for an AWS Lambda function. It is responsible for processing incoming events, in this case, it expects an event object and it can access information about the Lambda function's runtime environment via the context parameter.

  • Email Sending: The send_mail the function is called with the event parameter, which likely contains data to be included in the email.

Application

  • E-commerce Order Tracking: Serverless triggering and real-time notifications provide customers with timely order updates in the e-commerce industry.

  • IoT Device Monitoring: IoT sensor data triggers serverless functions to send real-time alerts about critical conditions.

  • Financial Alerts: Serverless functions send immediate financial notifications, from stock price changes to transaction confirmations.

  • Healthcare Patient Monitoring: Serverless notifications in healthcare alert professionals to deviations in patient vitals, improving care.

  • Social Media Engagement: Real-time notifications for likes, comments, and followers enhance social media user engagement.

  • Log and Error Monitoring: Serverless functions monitor logs and alert developers to errors for swift issue resolution.

  • Emergency Alerts: Serverless triggering and notifications are vital for disseminating emergency information to the public rapidly.

Conclusion

In the ever-evolving digital ecosystem, the collaboration between AWS Lambda and the NOVU API stands as a powerful solution for streamlining notifications. This integration simplifies the process of sending personalized emails and notifications, offering a scalable, cost-efficient, and versatile approach. The send_mail function acts as the bridge to connect your applications with NOVU's infrastructure, while the lambda_handler function ensures event-driven email dispatch. With an open-source ethos, a strong engineering community, and a commitment to security and compliance, this partnership paves the way for efficient, high-volume email delivery, whether for user engagement, marketing campaigns, or internal communications.

Did you find this article valuable?

Support Ankur by becoming a sponsor. Any amount is appreciated!