We are going to add an integration to our API Gateway REST API that will send events to our EventBridge event bus whenever the POST /dear-santa endpoint receives an HTTP POST request.
Add EventBridge event bus
Update your CDK stack with an event bus:
import { Construct, Stack, StackProps } from "aws-cdk-lib";
import { RestApi } from "aws-cdk-lib/aws-apigateway";
import { EventBus } from "aws-cdk-lib/aws-events";
export class EDAWorkshopStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const eventBus = new EventBus(this, "EDAWorkshopBus-YOUR_USER_NAME", {
eventBusName: "EDAWorkshopBus-YOUR_USER_NAME",
});
const api = new RestApi(this, "EDAWorkshopAPI-YOUR_USER_NAME");
const dearSanta = api.root.addResource("dear-santa");
dearSanta.addMethod("POST");
}
}
Bonus: Add a CloudWatch Log Group target to your Event Bus to forward all events as logs to CloudWatch
Permissions
Next, we need to give our API permission to put events on the bus. Add this to your stack:
import {
PolicyDocument,
PolicyStatement,
Role,
ServicePrincipal,
} from "aws-cdk-lib/aws-iam";
const apiRole = new Role(this, "EDAWorkshopAPIRole-YOUR_USER_NAME", {
assumedBy: new ServicePrincipal("apigateway"),
inlinePolicies: {
putEvents: new PolicyDocument({
statements: [
new PolicyStatement({
actions: ["events:PutEvents"],
resources: [eventBus.eventBusArn],
}),
],
}),
},
});
Now we can update our REST API with an API integration. In our case, this will be a direct integration between API Gateway and EventBridge - any requests sent to the POST /dear-santa endpoint will put an event on the bus. To do this, we need to add some more imports and update the dearSanta method:
Going back to the code you added to the stack, notice this line in the request template"Detail": "$util.escapeJavaScript($input.body)" - here we are passing the entire API request body to EventBridge. We need to make sure the request is valid before sending the data to EventBridge.
curl -X POST https://{YOUR_API_URL}.amazonaws.com/prod/dear-santa
The request should be rejected as it failed the validation you just added. Try updating your curl request with the expected body. You should receive the successful response from EventBridge!
Bonus: Update the model to only accept "lego" gift requests if a legoSKU is provided