Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create SAM App with Open Api #6

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added apigw-eventbridge/APIGateway-2-EventBridge.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
134 changes: 134 additions & 0 deletions apigw-eventbridge/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# AWS API Gateway to Amazon EventBridge

This pattern deploys an API Gateway HTTP API with a custom domain configuration and permissions to publish HTTP requests as an events to EventBridge.

Learn more about this pattern at Serverless Land Patterns: [https://serverlessland.com/patterns/apigateway-http-eventbridge-custom](https://serverlessland.com/patterns/apigateway-http-eventbridge-custom)

Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details.

## Requirements

* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed

## Deployment Instructions

1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
```
git clone https://github.com/aws-samples/serverless-patterns
```
1. Change directory to the pattern directory:
```
cd apigateway-eventbridge
```
1. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file:
```
sam deploy --guided
```
1. During the prompts:
* Enter a stack name
* Enter the desired AWS Region
* Allow SAM CLI to create IAM roles with the required permissions.

Once you have run `sam deploy -guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults.

1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing.

## How it works

The endpoint that will be created might look like, for example: `http://dev-events.example.com/apigw2eb/{source}/{detailType}`

Simply specify any `source` and `detailType` as a path parameters. The `body` of the request could be any valid json object.

### The AWS SAM template deploys the following resources

| Type | Logical ID |
| --- | --- |
| AWS::ApiGatewayV2::Api | HttpApi |
| AWS::Events::EventBus | ApplicationEventBus |
| AWS::ApiGatewayV2::Stage | HttpApiStage |
| AWS::ApiGatewayV2::ApiMapping | HttpApiMapping |
| AWS::IAM::Role | HttpApiIntegrationEventBridgeRole |
| AWS::ApiGatewayV2::Integration | HttpApiIntegrationEventBridge |
| AWS::ApiGatewayV2::Route | HttpApiRoute |
| AWS::CloudFormation::Stack1 | apigw2eb-[STAGE] |

When you send a HTTP POST request the API Gateway publishes an event to the custom event bus in EventBridge.

## Testing

Use your preffered terminal to send a http request.

```bash
curl --location --request POST 'https://dev-events.example.com/apigw2eb/mysource/mydetailtype' \
--header 'Content-Type: application/json' \
--data-raw '{
"mybody": {
"attr1": 1,
"attr2": [1,2]
}
}'
```

The response would be like:

```bash
{
"Entries": [
{
"EventId": "1a15592f-87a0-e0d8-8e21-172e63c57212"
}
],
"FailedEntryCount": 0
}
```

This means your event was published successfuly.

So, the Lambda event for the request above will look like:

```json
{
"version": "0",
"id": "1a15592f-87a0-e0d8-8e21-172e63c57594",
"detail-type": "mydetailtype",
"source": "com.mycompany.mysource",
"account": "xxxxxxxxxx74",
"time": "2021-04-03T14:45:32Z",
"region": "eu-central-1",
"resources": [],
"detail": {
"mybody": {
"attr1": 1,
"attr2": [1, 2]
}
}
}
```

Create your own either Lambda function or any other consumer for events you send with this API Gateway endpoint.

## Cleanup

1. Delete the stack
```bash
aws cloudformation delete-stack --stack-name STACK_NAME
```
1. Confirm the stack has been deleted
```bash
aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus"
```
----

## Additional resources

- [Amazon API Gateway V2](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_ApiGatewayV2.html)
- [Amazon EventBridge](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_Events.html)

---

Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
57 changes: 57 additions & 0 deletions apigw-eventbridge/pattern.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"title": "API Gateway to EventBridge",
"description": "Create an API Gateway that sends events to EventBridge.",
"architectureURL": "https://dobeerman-assets.s3.eu-central-1.amazonaws.com/APIGateway-2-EventBridge.png",
"videoId": "",
"level":"300",
"framework": "SAM",
"services": {
"from": "apigateway",
"to": "eventbridge"
},
"introBox": {
"headline": "How it works",
"text": [
"The endpoint that will be created might look like, for example: http://dev-events.example.com/apigw2eb/{source}/{detailType}",
"Simply specify any `source` and `detailType` as a path parameters. The body of the request could be any valid json object."
]
},
"deploy": {
"text": [
"sam deploy --guided"
]
},
"gitHub": {
"template": {
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-eventbridge",
"templateURL": "https://raw.githubusercontent.com/aws-samples/serverless-patterns/main/apigw-eventbridge/template.yaml",
"readmeURL": "https://raw.githubusercontent.com/aws-samples/serverless-patterns/main/apigw-eventbridge/README.md"
},
"payloads": [
{
"headline": "",
"payloadURL": ""
}
]
},
"resources": {
"headline": "Additional resources",
"bullets": [
{
"text": "Integrating Amazon EventBridge into your serverless applications",
"link": "https://aws.amazon.com/blogs/compute/integrating-amazon-eventbridge-into-your-serverless-applications/"
},
{
"text": "Use Amazon EventBridge to Build Decoupled, Event-Driven Architectures",
"link": "https://serverlessland.com/learn/eventbridge"
}
]
},
"author": {
"headline": "Presented by Alexander Smirnoff, Senior Software Engineer",
"name": "Alexander Smrinoff",
"imageURL": "https://dobeerman-assets.s3.eu-central-1.amazonaws.com/dobeerman_400x400.jpg",
"twitter": "beerman_",
"bio": "Alexander is a senior software engineer at Limehome GmbH."
}
}
144 changes: 144 additions & 0 deletions apigw-eventbridge/template.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Serverless pattern API Gateway to EventBridge

Parameters:
Stage:
Type: String
Default: dev
Service:
Type: String
Default: apigw2eb
SubDomainName:
Type: String
# Create a custom domain name at
# https://<REGION>.console.aws.amazon.com/apigateway/main/publish/domain-names
Default: dev-events
DomainName:
Type: String
# Replace example.com with your domain
Default: example.com

# Resources declares the AWS resources that you want to include in the stack
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html
Resources:
# Resource creates or updates a partner event bus or custom event bus
# https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbus.html
ApplicationEventBus:
Type: AWS::Events::EventBus
Properties:
Name: !Sub ${Service}-${Stage}

# Resource reates an API
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-api.html
HttpApi:
Type: AWS::ApiGatewayV2::Api
Properties:
Name: !Sub ${Service}-http-api-${Stage}
ProtocolType: HTTP
DisableExecuteApiEndpoint: true

# Resource creates an API mapping
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-apimapping.html
HttpApiMapping:
DependsOn:
- HttpApiStage
Type: AWS::ApiGatewayV2::ApiMapping
Properties:
ApiId:
Ref: HttpApi
DomainName: !Sub ${SubDomainName}.${DomainName}
Stage: !Sub ${Stage}
ApiMappingKey: !Sub ${Service}

# Resource updates a stage for an API
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html
HttpApiStage:
Type: AWS::ApiGatewayV2::Stage
Properties:
ApiId:
Ref: HttpApi
StageName: !Sub ${Stage}
AutoDeploy: true

# Resource creates a route for an API
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-route.html
HttpApiRoute:
DependsOn:
- HttpApiIntegrationEventBridge
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId:
Ref: HttpApi
RouteKey: POST /{source}/{detailType}
Target:
Fn::Join:
- /
- - integrations
- Ref: HttpApiIntegrationEventBridge

# Resource creates an integration for an API
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html
HttpApiIntegrationEventBridge:
DependsOn:
- HttpApiIntegrationEventBridgeRole
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId:
Ref: HttpApi
IntegrationType: AWS_PROXY
IntegrationSubtype: EventBridge-PutEvents
CredentialsArn:
Fn::GetAtt: [HttpApiIntegrationEventBridgeRole, Arn]
RequestParameters:
# Replace `mycompany` with your needs
Source: com.mycompany.$request.path.source
DetailType: $request.path.detailType
Detail: $request.body
EventBusName:
Fn::GetAtt: [ApplicationEventBus, Arn]
PayloadFormatVersion: "1.0"
TimeoutInMillis: 10000

# Resource creates a new role for your AWS account
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html
HttpApiIntegrationEventBridgeRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- apigateway.amazonaws.com
Action:
- sts:AssumeRole
Policies:
- PolicyName: !Sub ${Service}-${Stage}-eventBridge
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: 'events:*'
Resource:
Fn::GetAtt: [ApplicationEventBus, Arn]
RoleName:
Fn::Join:
- "-"
- - !Sub ${Service}-${Stage}
- Ref: AWS::Region
- eventBridgeRole

Outputs:
ApplicationEventBusName:
Description: Application EventBus Name
Value:
Ref: ApplicationEventBus

ApplicationEventBusArn:
Description: Application EventBus ARN
Value:
Fn::GetAtt:
- ApplicationEventBus
- Arn
Loading