CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-aws-cdk--aws-events-targets

Event targets for Amazon EventBridge that enable routing events to various AWS services

Overview
Eval results
Files

api-targets.mddocs/

API and HTTP Targets

Targets for REST APIs and HTTP endpoints that can receive EventBridge events via HTTP requests.

Capabilities

API Gateway Target

Invoke Amazon API Gateway REST APIs in response to EventBridge events.

/**
 * Use an API Gateway REST API as a target for Amazon EventBridge rules
 */
class ApiGateway implements events.IRuleTarget {
  readonly restApi:api.RestApi;
  
  constructor(restApi: api.RestApi, props?: ApiGatewayProps);
  
  /**
   * Returns a RuleTarget that can be used to trigger this API Gateway REST API
   * as a result from an EventBridge event
   */
  bind(rule: events.IRule, id?: string): events.RuleTargetConfig;
}

interface ApiGatewayProps extends TargetBaseProps {
  /**
   * The method for API resource invoked by the rule
   * @default '*' that treated as ANY
   */
  readonly method?: string;
  
  /**
   * The API resource invoked by the rule
   * Wildcards ('*') can be used, requiring equal pathParameterValues
   * @default '/'
   */
  readonly path?: string;
  
  /**
   * The deploy stage of API gateway invoked by the rule
   * @default the value of deploymentStage.stageName of target API Gateway
   */
  readonly stage?: string;
  
  /**
   * The headers to be set when requesting API
   * @default no header parameters
   */
  readonly headerParameters?: { [key: string]: string };
  
  /**
   * The path parameter values to populate wildcards ("*") in the API path
   * @default no path parameters
   */
  readonly pathParameterValues?: string[];
  
  /**
   * The query parameters to be set when requesting API
   * @default no querystring parameters
   */
  readonly queryStringParameters?: { [key: string]: string };
  
  /**
   * This will be the POST request body sent to the API
   * @default the entire EventBridge event
   */
  readonly postBody?: events.RuleTargetInput;
  
  /**
   * The role to assume before invoking the target
   * @default a new role will be created
   */
  readonly eventRole?: iam.IRole;
}

Usage Example:

import * as api from "@aws-cdk/aws-apigateway";
import * as lambda from "@aws-cdk/aws-lambda";
import * as events from "@aws-cdk/aws-events";
import * as targets from "@aws-cdk/aws-events-targets";
import * as sqs from "@aws-cdk/aws-sqs";

// Create Lambda function for API
const apiHandler = new lambda.Function(this, "ApiHandler", {
  runtime: lambda.Runtime.NODEJS_14_X,
  handler: "index.handler",
  code: lambda.Code.fromInline(`
    exports.handler = async (event) => {
      console.log('Received event:', JSON.stringify(event, null, 2));
      return { statusCode: 200, body: 'Event processed' };
    };
  `),
});

// Create API Gateway
const restApi = new api.LambdaRestApi(this, "EventApi", {
  handler: apiHandler,
  proxy: false,
});

// Add resources and methods
const webhooks = restApi.root.addResource("webhooks");
const eventResource = webhooks.addResource("events");
eventResource.addMethod("POST");

// Create rule for custom application events
const rule = new events.Rule(this, "AppEventRule", {
  eventPattern: {
    source: ["myapp.users"],
    detailType: ["User Registration", "User Login"],
  },
});

// Create dead letter queue
const dlq = new sqs.Queue(this, "ApiDlq");

// Add API Gateway target with path parameters
rule.addTarget(new targets.ApiGateway(restApi, {
  path: "/webhooks/events",
  method: "POST",
  stage: "prod",
  headerParameters: {
    "X-Event-Source": "eventbridge",
    "X-Event-Type": events.EventField.fromPath("$.detail-type"),
  },
  queryStringParameters: {
    source: events.EventField.fromPath("$.source"),
    account: events.EventField.fromPath("$.account"),
  },
  postBody: events.RuleTargetInput.fromObject({
    eventId: events.EventField.fromPath("$.id"),
    timestamp: events.EventField.fromPath("$.time"),
    eventType: events.EventField.fromPath("$.detail-type"),
    payload: events.EventField.fromPath("$.detail"),
  }),
  deadLetterQueue: dlq,
  retryAttempts: 2,
  maxEventAge: Duration.hours(1),
}));

// API with wildcards and path parameters
const wildcardRule = new events.Rule(this, "WildcardRule", {
  eventPattern: {
    source: ["myapp.resources"],
  },
});

wildcardRule.addTarget(new targets.ApiGateway(restApi, {
  path: "/*/test/*",
  method: "GET",
  pathParameterValues: [
    events.EventField.fromPath("$.detail.resourceType"),
    events.EventField.fromPath("$.detail.resourceId"),
  ],
}));

API Destination Target

Send events to external HTTP endpoints using EventBridge API destinations.

/**
 * Use API destinations as EventBridge targets
 */
class ApiDestination implements events.IRuleTarget {
  constructor(apiDestination: events.IApiDestination, props?: ApiDestinationProps);
  
  /**
   * Returns a RuleTarget that can be used to trigger this API destination
   * as a result from an EventBridge event
   */
  bind(rule: events.IRule, id?: string): events.RuleTargetConfig;
}

interface ApiDestinationProps extends TargetBaseProps {
  /**
   * The event to send to the API destination
   * @default the entire EventBridge event
   */
  readonly event?: events.RuleTargetInput;
  
  /**
   * The role to assume before invoking the target
   * @default a new role will be created
   */
  readonly eventRole?: iam.IRole;
  
  /**
   * Additional headers to send with the request
   * @default no additional headers
   */
  readonly headerParameters?: Record<string, string>;
  
  /**
   * Path parameters for wildcards in the destination endpoint URL
   * @default no path parameters
   */
  readonly pathParameterValues?: string[];
  
  /**
   * Additional query parameters to send with the request
   * @default no additional query parameters
   */
  readonly queryStringParameters?: Record<string, string>;
}

Usage Example:

import * as events from "@aws-cdk/aws-events";
import * as targets from "@aws-cdk/aws-events-targets";
import { SecretValue } from "@aws-cdk/core";

// Create connection with API key authentication
const connection = new events.Connection(this, "WebhookConnection", {
  authorization: events.Authorization.apiKey(
    "x-api-key", 
    SecretValue.secretsManager("webhook-api-key")
  ),
  description: "Connection to external webhook service",
});

// Create API destination
const destination = new events.ApiDestination(this, "WebhookDestination", {
  connection,
  endpoint: "https://api.example.com/webhooks/events",
  description: "External webhook for processing events",
  rateLimitPerSecond: 10,
});

// Create rule for order events
const orderRule = new events.Rule(this, "OrderRule", {
  eventPattern: {
    source: ["myapp.orders"],
    detailType: ["Order Created", "Order Updated", "Order Cancelled"],
  },
});

// Add API destination target
orderRule.addTarget(new targets.ApiDestination(destination, {
  headerParameters: {
    "X-Event-Source": "aws-eventbridge",
    "X-Customer-Id": events.EventField.fromPath("$.detail.customerId"),
  },
  queryStringParameters: {
    timestamp: events.EventField.fromPath("$.time"),
    region: events.EventField.fromPath("$.region"),
  },
  event: events.RuleTargetInput.fromObject({
    orderId: events.EventField.fromPath("$.detail.orderId"),
    status: events.EventField.fromPath("$.detail.status"),
    amount: events.EventField.fromPath("$.detail.amount"),
    currency: events.EventField.fromPath("$.detail.currency"),
    timestamp: events.EventField.fromPath("$.time"),
  }),
  retryAttempts: 3,
  maxEventAge: Duration.hours(6),
}));

// Simple usage with OAuth authentication
const oauthConnection = new events.Connection(this, "OAuthConnection", {
  authorization: events.Authorization.oauth({
    authorizationEndpoint: "https://auth.example.com/oauth/authorize",
    clientId: "my-client-id",
    clientSecret: SecretValue.secretsManager("oauth-client-secret"),
    httpMethod: events.HttpMethod.POST,
  }),
});

const oauthDestination = new events.ApiDestination(this, "OAuthDestination", {
  connection: oauthConnection,
  endpoint: "https://api.partner.com/events",
});

const simpleRule = new events.Rule(this, "SimpleRule", {
  schedule: events.Schedule.rate(Duration.minutes(15)),
});

simpleRule.addTarget(new targets.ApiDestination(oauthDestination));

Authentication Patterns

API Key Authentication

import * as events from "@aws-cdk/aws-events";
import { SecretValue } from "@aws-cdk/core";

const apiKeyConnection = new events.Connection(this, "ApiKeyConnection", {
  authorization: events.Authorization.apiKey("Authorization", SecretValue.secretsManager("bearer-token")),
});

OAuth Authentication

const oauthConnection = new events.Connection(this, "OAuthConnection", {
  authorization: events.Authorization.oauth({
    authorizationEndpoint: "https://auth.provider.com/oauth/authorize",
    clientId: "client-id",
    clientSecret: SecretValue.secretsManager("oauth-secret"),
    httpMethod: events.HttpMethod.POST,
    bodyParameters: {
      scope: "events:write",
    },
    queryStringParameters: {
      audience: "api.provider.com",
    },
  }),
});

Basic Authentication

const basicConnection = new events.Connection(this, "BasicConnection", {
  authorization: events.Authorization.basic("username", SecretValue.secretsManager("password")),
});

Request Customization

Custom Headers and Parameters

// Dynamic headers from event data
const target = new targets.ApiDestination(destination, {
  headerParameters: {
    "X-Event-ID": events.EventField.fromPath("$.id"),
    "X-Source": events.EventField.fromPath("$.source"),
    "Content-Type": "application/json",
  },
  queryStringParameters: {
    version: "v1",
    format: "json",
    timestamp: events.EventField.fromPath("$.time"),
  },
});

Request Body Transformation

// Custom payload structure
const customPayload = events.RuleTargetInput.fromObject({
  webhook: {
    id: events.EventField.fromPath("$.id"),
    timestamp: events.EventField.fromPath("$.time"),
    source: {
      service: events.EventField.fromPath("$.source"),
      region: events.EventField.fromPath("$.region"),
      account: events.EventField.fromPath("$.account"),
    },
    data: events.EventField.fromPath("$.detail"),
  },
});

Install with Tessl CLI

npx tessl i tessl/npm-aws-cdk--aws-events-targets

docs

analytics-targets.md

api-targets.md

cicd-targets.md

compute-targets.md

index.md

messaging-targets.md

orchestration-targets.md

system-targets.md

tile.json