Amazon API Gateway to Amazon EventBridge using Amazon Serverless Application Model (SAM)

Amazon API Gateway to Amazon EventBridge using Amazon Serverless Application Model (SAM)

Amazon API Gateway is a fully managed service provided by AWS that makes it easy for developers to create, publish, maintain, monitor, and secure APIs at any scale. It acts as a front door to your backend services, allowing you to expose your applications, services, or serverless functions to the internet or your internal network.

Amazon EventBridge is a fully managed event bus service provided by AWS that simplifies building event-driven applications and integrating AWS services, SaaS applications, and custom applications. It allows you to easily connect and coordinate different services and systems in a serverless, event-driven architecture.

This article discusses the integration of Amazon API Gateway with Amazon EventBridge. There are two common approaches to sending events from API Gateway to EventBridge.

  • Indirect Integration via Lambda
  • Direct Integration

In the Indirect Integration approach, the API Gateway forwards the request to a Lambda function. The Lambda function processes the incoming request, potentially transforming or validating the data. The Lambda function then uses an SDK or direct HTTP call to send the event to EventBridge. This method allows for additional processing or validation of the event data before sending it to EventBridge.

The Direct Integration approach involves configuring an API Gateway resource/method to integrate with EventBridge using the x-amazon-apigateway-integration property directly. This method provides a direct way to forward events to EventBridge without going through a Lambda function.

Both approaches have their pros and cons, and the choice between them depends on your specific use case and requirements. The direct integration approach is simpler and more direct, while the Lambda intermediary approach offers more flexibility for processing and validating event data before sending it to EventBridge.

Let us further explore the Direct Integration approach. Follow the following steps to enable an API Gateway to integrate with EventBridge directly:

1. Create EventBus

MyEventBus:
    Type: AWS::Events::EventBus
    Properties: 
      Name: MyEventBus
        

2. API Gateway role with permissions to put event.

The API must have permission to put the event on the event bus.

ApiGatewayEventBridgeRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: 'sts:AssumeRole'
            Principal:
              Service:
                - apigateway.amazonaws.com
      Policies:
        - PolicyName: EBPutEvents
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - 'events:PutEvents'
                Resource:
                  - !GetAtt  MyEventBus.Arn
        

3. Create API Gateway

Api:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Dev
      DefinitionBody:
        openapi: '3.0'
        info: {}
        paths:
          /:
            post:
              responses:
                "200":
                  description: "200 response"
              x-amazon-apigateway-integration:
                type: "aws"
                uri:
                  Fn::Sub: "arn:aws:apigateway:${AWS::Region}:events:action/PutEvents"
                credentials: !GetAtt  ApiGatewayEventBridgeRole.Arn
                httpMethod: "POST"
                requestTemplates:
                  application/json: !Sub 
                    - |-
                      #set($context.requestOverride.header.X-Amz-Target = "AWSEvents.PutEvents")
                      #set($context.requestOverride.header.Content-Type = "application/x-amz-json-1.1") 
                      {
                        "Entries": [
                          {
                            "Detail": "$util.escapeJavaScript($input.body)",
                            "DetailType": "DetailType",
                            "Source": "API-Gateway",
                            "EventBusName": "${EventBusName}"
                          }
                        ]
                      }
                    - { EventBusName: !Ref MyEventBus }
                responses:
                  default:
                    statusCode: "200"
                passthroughBehavior: "when_no_templates"
        

We have defined an API of type AWS::Serverless::Api on Dev stage. We have defined a POST method for `/` path. This integration is defined under x-amazon-apigateway-integration tag. The integration type is set to "aws" and the uri points to the EventBridge's PutEvents action ARN. The requestTemplates defines the conversion of received request into the format that is acceptable by the AWS API to perform the PutEvents action. The credentials tag points towards the role which was created in step 2. In the event payload, EventBusName is the name of the Event Bus on which we want to put the events. Learn more about the API definition here.

Note: The Source field in an event payload represents the origin or the source of the event. It allows you to distinguish between different types or sources of events.

4. Lambda function invoked from EventBridge

To complete the flow create a Lambda function to log the events received from EventBridge.

MyTriggeredLambda:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: TriggeredLambda/
      Handler: com.example.App::handleRequest
      Runtime: java11
      Architectures:
        - x86_64
      Timeout: 30
      MemorySize: 512
      Environment:
        Variables:
          JAVA_TOOL_OPTIONS: -XX:+TieredCompilation -XX:TieredStopAtLevel=1 
      Events:
        EventBridgeTrigger:
          Type: EventBridgeRule
          Properties:
            EventBusName: MyEventBus
            Pattern:
              source:
                - API-Gateway
        

Note: This lambda is triggered when an event is received from the source API-Gateway

The Java code of lambda is

package com.example;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;

public class App {

    public void handleRequest(final Object event, final Context context) {
        LambdaLogger logger = context.getLogger();
        logger.log(event.toString());
    }
}
        


This comprehensive overview highlights the integration of Amazon API Gateway with Amazon EventBridge, offering two distinct approaches: Indirect Integration via Lambda and Direct Integration. The former leverages an intermediary Lambda function to process and potentially transform event data before sending it to EventBridge. On the other hand, the latter involves the direct configuration of API Gateway to integrate seamlessly with EventBridge, streamlining the event forwarding process. Both approaches possess unique strengths and considerations, allowing developers to select the one best suited to their specific use case. By employing these integration techniques, organizations can efficiently manage event-driven architectures, ensuring seamless coordination between services and systems.

To view or add a comment, sign in

More articles by Ahsan Qadeer

Others also viewed

Explore content categories