Skip to main content
search

AWS Lambda to API Gateway to Amazon EventBridge (CloudWatch Events)

By August 26, 2023December 12th, 2023DevOps
Using AWS Lambda with Amazon EventBridge CloudWatch Events

AWS Lambda: Run code without thinking about servers or clusters.

AWS Lambda is a serverless, event-driven compute service that lets you run code for virtually any type of application or backend service without provisioning or managing servers. You can trigger Lambda from over 200 AWS services and software as a service (SaaS) applications and only pay for what you use.

Lambda counts a request each time it starts executing in response to an event notification trigger, such as from Amazon Simple Notification Service (SNS) or Amazon EventBridge, or an invoke call, such as from Amazon API Gateway, or via the AWS SDK, including test invokes from the AWS Console.

AWS architecture for a simple web application that checks weather conditions:

AWS Lambda

 

For Creating Lambda

Step 1: Creating Function

We need to create a Lambda Function by going to the functions tab, clicking the Create Function button, and fill the details like Function name, Runtime environment, Architecture, and roles with permissions to upload logs to Amazon CloudWatch Logs.

Creating Lambda Funtion

Step 2: Upload or create Application code

  • We will redirect to the Runtime Environment, here we can create our Application code
  • Every code is called inside the event handler function

Code sequre

The boiler plate code created by lambda for a nodejs function is always inside a exports.handler function. This is the function that gets called when the lambda runs.

  • There can only be one index.js file in a lambda and there can only be one handler inside it
  • Exports function should always return response json object with a statusCode and body. Body has to a JSON stringified and the statusCode can we any of the codes supported in HTTP protocol. (This is required so that the lambda does not crash with internal server error)

 

create Application code

 

Testing of lambda can be done directly from the console using the test button. We can even pass json object as input which will be a part of the event object in the exports.handler

TO Export the function

To Use NPM Packages and other dependencies we have to export the lambda function into our local folder then we can use that in our IDE to install Third-party dependencies

Export the function

 

TO Import the function

We can push our code to AWS Lambda function using IDE when we configure AWS using aws config command on Terminal or else we can .zip our code and click upload from button to add the code with the function.

After uploading the code from the local here the lambda function looks like,
We install joi form npm package for example

API Gateway

You can create a web API with an HTTP endpoint for your Lambda function by using Amazon API Gateway. API Gateway provides tools for creating and documenting web APIs that route HTTP requests to Lambda functions. You can secure access to your API with authentication and authorization controls. Your APIs can serve traffic over the internet or can be accessible only within your VPC.

Resources in your API define one or more methods, such as GET or POST. Methods have an integration that routes requests to a Lambda function or another integration type. You can define each resource and method individually, or use special resource and method types to match all requests that fit a pattern. A proxy resource catches all paths beneath a resource. The ANY method catches all HTTP methods.

Api gatway

 

Click Create API and select Rest API to create API for the lambda function

Rest Api Gatway

 

To create Endpoint methods

Click Action -> Create method to create GET, POST, PUT, PATCH etc..

create endpoint methods 1024x913 1

 

After creating methods we need to connect the Rest API with Lambda function by selecting the lambda function we need to connect.

Rest API with Lambda

 

Once its done the API need to be Deployed by clicking Action -> Deploy API

Deploy API

 

Once deployed we will get the invoke URL like provided below

save changes

 

 

We can create multiple routes and methods for a lambda functions

 

To create Endpoint methods 5

 

Amazon Cloud Watch

You can use a Lambda function to monitor and analyze logs from an Amazon CloudWatch Logs log stream. Create subscriptions for one or more log streams to invoke a function when logs are created or match an optional pattern. Use the function to send a notification or persist the log to a database or storage.

CloudWatch Logs invokes your function asynchronously with an event that contains log data. The value of the data field is a Base64-encoded .gzip file archive.

We can check logs by clicking the monitor tab on the function to see view logs in cloudWatch button

Amazon Cloud Watch

For Each call, it will create separate log files

The Logs

Whatever we put in the console.log in the lambda function will comes in that log file

Amazon Event Bridge

Amazon EventBridge is a serverless event bus service that you can use to connect your applications with data from a variety of sources. EventBridge delivers a stream of real-time data from your applications, software as a service (SaaS) applications, and AWS services to targets such as AWS Lambda functions, HTTP invocation endpoints using API destinations, or event buses in other AWS accounts.
It is the next version of Amazon CloudWatch Events. Event bridge can be used to connect with a long list of aws services like lambda, api gateway, ses, ec2 etc. It also supports custom rest api endpoint and many 3rd party services like zendesk, Jira etc.

Why should you use EventBridge

• Scalability: EventBridge scales automatically to handle the volume of events you send to it.
• Simplified Architecture: It allows you to create event-driven architectures without the need to manage infrastructure.
• Event Filtering: You can filter events to ensure that only the relevant events are routed to specific targets.
• Reliability: EventBridge is built on the popular AWS service CloudWatch Events and offers the same level of reliability and durability.

How EventBridge Works

EventBridge consists of three main components:

• Event Producers: Sources that generate events. These can be AWS services, integrated SaaS applications, or your custom applications.
• Event Bus: It’s a custom or default event bus where events are sent to be routed to different targets.
• Event Targets: Services that handle events. For example, AWS Lambda, Amazon SNS, or Amazon SQS.

Integration with API Gateway and AWS Lambda

• Set up an API Gateway: Create an API in the API Gateway console. Add a POST method and point it to the EventBridge event bus.

• Create an EventBridge rule: In the EventBridge console, create a rule and choose the event bus you previously defined. Set the source as the API Gateway and specify the event pattern. Set the target as the AWS Lambda function.

• Create a Lambda function: In the AWS Lambda console, create a new function with the Node.js runtime. Define a handler that processes the event data and performs the desired action.

• Send a POST request: Using a tool like Postman, send a POST request to the API Gateway URL with the desired event data in the request body.

• Process the event: EventBridge captures the event and routes it to the specified Lambda function based on the defined rule. The Lambda function processes the event and executes the defined logic.

Integration with API Gateway and AWS Lambda

 

In conclusion, EventBridge offers a simple yet powerful way to handle events in your applications. By integrating with other AWS services, you can create efficient and scalable event-driven architectures. I hope this blog helps you understand the potential of EventBridge and motivates you to explore its features further. Happy coding!

Raj Sanghvi

Raj Sanghvi is a technologist and founder of BitCot, a full-service award-winning software development company. With over 15 years of innovative coding experience creating complex technology solutions for businesses like IBM, Sony, Nissan, Micron, Dicks Sporting Goods, HDSupply, Bombardier and more, Sanghvi helps build for both major brands and entrepreneurs to launch their own technologies platforms. Visit Raj Sanghvi on LinkedIn and follow him on Twitter. View Full Bio

Leave a Reply