or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

analytics-targets.mdapi-targets.mdcicd-targets.mdcompute-targets.mdindex.mdmessaging-targets.mdorchestration-targets.mdsystem-targets.md

api-targets.mddocs/

0

# API and HTTP Targets

1

2

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

3

4

## Capabilities

5

6

### API Gateway Target

7

8

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

9

10

```typescript { .api }

11

/**

12

* Use an API Gateway REST API as a target for Amazon EventBridge rules

13

*/

14

class ApiGateway implements events.IRuleTarget {

15

readonly restApi:api.RestApi;

16

17

constructor(restApi: api.RestApi, props?: ApiGatewayProps);

18

19

/**

20

* Returns a RuleTarget that can be used to trigger this API Gateway REST API

21

* as a result from an EventBridge event

22

*/

23

bind(rule: events.IRule, id?: string): events.RuleTargetConfig;

24

}

25

26

interface ApiGatewayProps extends TargetBaseProps {

27

/**

28

* The method for API resource invoked by the rule

29

* @default '*' that treated as ANY

30

*/

31

readonly method?: string;

32

33

/**

34

* The API resource invoked by the rule

35

* Wildcards ('*') can be used, requiring equal pathParameterValues

36

* @default '/'

37

*/

38

readonly path?: string;

39

40

/**

41

* The deploy stage of API gateway invoked by the rule

42

* @default the value of deploymentStage.stageName of target API Gateway

43

*/

44

readonly stage?: string;

45

46

/**

47

* The headers to be set when requesting API

48

* @default no header parameters

49

*/

50

readonly headerParameters?: { [key: string]: string };

51

52

/**

53

* The path parameter values to populate wildcards ("*") in the API path

54

* @default no path parameters

55

*/

56

readonly pathParameterValues?: string[];

57

58

/**

59

* The query parameters to be set when requesting API

60

* @default no querystring parameters

61

*/

62

readonly queryStringParameters?: { [key: string]: string };

63

64

/**

65

* This will be the POST request body sent to the API

66

* @default the entire EventBridge event

67

*/

68

readonly postBody?: events.RuleTargetInput;

69

70

/**

71

* The role to assume before invoking the target

72

* @default a new role will be created

73

*/

74

readonly eventRole?: iam.IRole;

75

}

76

```

77

78

**Usage Example:**

79

80

```typescript

81

import * as api from "@aws-cdk/aws-apigateway";

82

import * as lambda from "@aws-cdk/aws-lambda";

83

import * as events from "@aws-cdk/aws-events";

84

import * as targets from "@aws-cdk/aws-events-targets";

85

import * as sqs from "@aws-cdk/aws-sqs";

86

87

// Create Lambda function for API

88

const apiHandler = new lambda.Function(this, "ApiHandler", {

89

runtime: lambda.Runtime.NODEJS_14_X,

90

handler: "index.handler",

91

code: lambda.Code.fromInline(`

92

exports.handler = async (event) => {

93

console.log('Received event:', JSON.stringify(event, null, 2));

94

return { statusCode: 200, body: 'Event processed' };

95

};

96

`),

97

});

98

99

// Create API Gateway

100

const restApi = new api.LambdaRestApi(this, "EventApi", {

101

handler: apiHandler,

102

proxy: false,

103

});

104

105

// Add resources and methods

106

const webhooks = restApi.root.addResource("webhooks");

107

const eventResource = webhooks.addResource("events");

108

eventResource.addMethod("POST");

109

110

// Create rule for custom application events

111

const rule = new events.Rule(this, "AppEventRule", {

112

eventPattern: {

113

source: ["myapp.users"],

114

detailType: ["User Registration", "User Login"],

115

},

116

});

117

118

// Create dead letter queue

119

const dlq = new sqs.Queue(this, "ApiDlq");

120

121

// Add API Gateway target with path parameters

122

rule.addTarget(new targets.ApiGateway(restApi, {

123

path: "/webhooks/events",

124

method: "POST",

125

stage: "prod",

126

headerParameters: {

127

"X-Event-Source": "eventbridge",

128

"X-Event-Type": events.EventField.fromPath("$.detail-type"),

129

},

130

queryStringParameters: {

131

source: events.EventField.fromPath("$.source"),

132

account: events.EventField.fromPath("$.account"),

133

},

134

postBody: events.RuleTargetInput.fromObject({

135

eventId: events.EventField.fromPath("$.id"),

136

timestamp: events.EventField.fromPath("$.time"),

137

eventType: events.EventField.fromPath("$.detail-type"),

138

payload: events.EventField.fromPath("$.detail"),

139

}),

140

deadLetterQueue: dlq,

141

retryAttempts: 2,

142

maxEventAge: Duration.hours(1),

143

}));

144

145

// API with wildcards and path parameters

146

const wildcardRule = new events.Rule(this, "WildcardRule", {

147

eventPattern: {

148

source: ["myapp.resources"],

149

},

150

});

151

152

wildcardRule.addTarget(new targets.ApiGateway(restApi, {

153

path: "/*/test/*",

154

method: "GET",

155

pathParameterValues: [

156

events.EventField.fromPath("$.detail.resourceType"),

157

events.EventField.fromPath("$.detail.resourceId"),

158

],

159

}));

160

```

161

162

### API Destination Target

163

164

Send events to external HTTP endpoints using EventBridge API destinations.

165

166

```typescript { .api }

167

/**

168

* Use API destinations as EventBridge targets

169

*/

170

class ApiDestination implements events.IRuleTarget {

171

constructor(apiDestination: events.IApiDestination, props?: ApiDestinationProps);

172

173

/**

174

* Returns a RuleTarget that can be used to trigger this API destination

175

* as a result from an EventBridge event

176

*/

177

bind(rule: events.IRule, id?: string): events.RuleTargetConfig;

178

}

179

180

interface ApiDestinationProps extends TargetBaseProps {

181

/**

182

* The event to send to the API destination

183

* @default the entire EventBridge event

184

*/

185

readonly event?: events.RuleTargetInput;

186

187

/**

188

* The role to assume before invoking the target

189

* @default a new role will be created

190

*/

191

readonly eventRole?: iam.IRole;

192

193

/**

194

* Additional headers to send with the request

195

* @default no additional headers

196

*/

197

readonly headerParameters?: Record<string, string>;

198

199

/**

200

* Path parameters for wildcards in the destination endpoint URL

201

* @default no path parameters

202

*/

203

readonly pathParameterValues?: string[];

204

205

/**

206

* Additional query parameters to send with the request

207

* @default no additional query parameters

208

*/

209

readonly queryStringParameters?: Record<string, string>;

210

}

211

```

212

213

**Usage Example:**

214

215

```typescript

216

import * as events from "@aws-cdk/aws-events";

217

import * as targets from "@aws-cdk/aws-events-targets";

218

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

219

220

// Create connection with API key authentication

221

const connection = new events.Connection(this, "WebhookConnection", {

222

authorization: events.Authorization.apiKey(

223

"x-api-key",

224

SecretValue.secretsManager("webhook-api-key")

225

),

226

description: "Connection to external webhook service",

227

});

228

229

// Create API destination

230

const destination = new events.ApiDestination(this, "WebhookDestination", {

231

connection,

232

endpoint: "https://api.example.com/webhooks/events",

233

description: "External webhook for processing events",

234

rateLimitPerSecond: 10,

235

});

236

237

// Create rule for order events

238

const orderRule = new events.Rule(this, "OrderRule", {

239

eventPattern: {

240

source: ["myapp.orders"],

241

detailType: ["Order Created", "Order Updated", "Order Cancelled"],

242

},

243

});

244

245

// Add API destination target

246

orderRule.addTarget(new targets.ApiDestination(destination, {

247

headerParameters: {

248

"X-Event-Source": "aws-eventbridge",

249

"X-Customer-Id": events.EventField.fromPath("$.detail.customerId"),

250

},

251

queryStringParameters: {

252

timestamp: events.EventField.fromPath("$.time"),

253

region: events.EventField.fromPath("$.region"),

254

},

255

event: events.RuleTargetInput.fromObject({

256

orderId: events.EventField.fromPath("$.detail.orderId"),

257

status: events.EventField.fromPath("$.detail.status"),

258

amount: events.EventField.fromPath("$.detail.amount"),

259

currency: events.EventField.fromPath("$.detail.currency"),

260

timestamp: events.EventField.fromPath("$.time"),

261

}),

262

retryAttempts: 3,

263

maxEventAge: Duration.hours(6),

264

}));

265

266

// Simple usage with OAuth authentication

267

const oauthConnection = new events.Connection(this, "OAuthConnection", {

268

authorization: events.Authorization.oauth({

269

authorizationEndpoint: "https://auth.example.com/oauth/authorize",

270

clientId: "my-client-id",

271

clientSecret: SecretValue.secretsManager("oauth-client-secret"),

272

httpMethod: events.HttpMethod.POST,

273

}),

274

});

275

276

const oauthDestination = new events.ApiDestination(this, "OAuthDestination", {

277

connection: oauthConnection,

278

endpoint: "https://api.partner.com/events",

279

});

280

281

const simpleRule = new events.Rule(this, "SimpleRule", {

282

schedule: events.Schedule.rate(Duration.minutes(15)),

283

});

284

285

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

286

```

287

288

## Authentication Patterns

289

290

### API Key Authentication

291

292

```typescript

293

import * as events from "@aws-cdk/aws-events";

294

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

295

296

const apiKeyConnection = new events.Connection(this, "ApiKeyConnection", {

297

authorization: events.Authorization.apiKey("Authorization", SecretValue.secretsManager("bearer-token")),

298

});

299

```

300

301

### OAuth Authentication

302

303

```typescript

304

const oauthConnection = new events.Connection(this, "OAuthConnection", {

305

authorization: events.Authorization.oauth({

306

authorizationEndpoint: "https://auth.provider.com/oauth/authorize",

307

clientId: "client-id",

308

clientSecret: SecretValue.secretsManager("oauth-secret"),

309

httpMethod: events.HttpMethod.POST,

310

bodyParameters: {

311

scope: "events:write",

312

},

313

queryStringParameters: {

314

audience: "api.provider.com",

315

},

316

}),

317

});

318

```

319

320

### Basic Authentication

321

322

```typescript

323

const basicConnection = new events.Connection(this, "BasicConnection", {

324

authorization: events.Authorization.basic("username", SecretValue.secretsManager("password")),

325

});

326

```

327

328

## Request Customization

329

330

### Custom Headers and Parameters

331

332

```typescript

333

// Dynamic headers from event data

334

const target = new targets.ApiDestination(destination, {

335

headerParameters: {

336

"X-Event-ID": events.EventField.fromPath("$.id"),

337

"X-Source": events.EventField.fromPath("$.source"),

338

"Content-Type": "application/json",

339

},

340

queryStringParameters: {

341

version: "v1",

342

format: "json",

343

timestamp: events.EventField.fromPath("$.time"),

344

},

345

});

346

```

347

348

### Request Body Transformation

349

350

```typescript

351

// Custom payload structure

352

const customPayload = events.RuleTargetInput.fromObject({

353

webhook: {

354

id: events.EventField.fromPath("$.id"),

355

timestamp: events.EventField.fromPath("$.time"),

356

source: {

357

service: events.EventField.fromPath("$.source"),

358

region: events.EventField.fromPath("$.region"),

359

account: events.EventField.fromPath("$.account"),

360

},

361

data: events.EventField.fromPath("$.detail"),

362

},

363

});

364

```