How To Put Event Data On AWS Event Bus Using Lambda?

Reading Time: 2 minutes

In this article, we will talk about how to put event data on AWS event bus using Lambda.

This article will help you adapt serverless architecture as it involves one of the standard core data flow models that involve API Gateway, Lambda, and a data processing service such as AWS EventBridge in our case.

Throughout the article, we will be taking the help of AWS services to achieve this but you can replicate the same thing on other cloud providers or even your on-premise setup as well.

Both EventBridge and SQS provide messaging patterns for your serverless setup whether it is simple messaging or pub/sub.

What Is AWS EventBridge?

AWS EventBridge is a serverless, fully managed, and scalable event bus as a service by AWS that can be used to integrate multiple services using event data.

But, what is an event bus? I will keep things simple here, you can think of an event as data and a bus as a wire that connects two systems together.

And yes, it’s the same bus that they teach you about in engineering colleges/schools. Remember bus topologies? That was nothing but a different arrangement of wires to achieve multiple use cases.

The event bus here is also the same, except it’s on the cloud and it is managed and scalable.

How To Put Event Data On AWS Event Bus Using Lambda?

Now that you understand what is an event bus, let us now see how you can put and retrive event data using it.

Your data input/output flow might look like anything so for this tutorial, we will take our data from a Lambda function. You can easily adjust for your use case accordingly.

Our data comes through API Gateway and using Lambda Proxy Integration, we get all the request data like headers, body, etc in our Lambda code.

This is how you can put that data on an event bus using Python 3.7 Lambda and boto3 library:

import logging
import json
import hmac
import hashlib
import re
import datetime
import boto3
import base64

from botocore.exceptions import ClientError
from urllib.parse import unquote

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

events = boto3.client("events")


def process(content):
    entries = [
        {
            "Source": "my.custom.source",
            "DetailType": "description",
            "Detail": content,
            "EventBusName": "default",
        }
    ]
    event_response = events.put_events(Entries=entries)


def lambda_handler(event, context):
    process(event["body"])

This code will put all your event data on the default event bus. You can also configure your own custom event bus with custom rules.

Written by 

Mohit Saxena is a Software Consultant having experience of more than 2 years. He is always up for new challenges and loves to aggressively move towards completing the software requirements. On a personal front, he loves to climb mountains and is a big foodie.

Leave a Reply