Skip to content

Commit 2f0adfc

Browse files
Cesar IzquierdoCesar Izquierdo
Cesar Izquierdo
authored and
Cesar Izquierdo
committed
feat: add pattern to connect http api and eventbridge with CDK in Python
1 parent a666025 commit 2f0adfc

File tree

9 files changed

+451
-0
lines changed

9 files changed

+451
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
.DS_Store
2+
# Byte-compiled / optimized / DLL files
3+
__pycache__/
4+
*.py[cod]
5+
*$py.class
6+
7+
# C extensions
8+
*.so
9+
10+
# Distribution / packaging
11+
.Python
12+
build/
13+
develop-eggs/
14+
dist/
15+
downloads/
16+
eggs/
17+
.eggs/
18+
lib/
19+
lib64/
20+
parts/
21+
sdist/
22+
var/
23+
wheels/
24+
pip-wheel-metadata/
25+
share/python-wheels/
26+
*.egg-info/
27+
.installed.cfg
28+
*.egg
29+
MANIFEST
30+
31+
# PyInstaller
32+
# Usually these files are written by a python script from a template
33+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
34+
*.manifest
35+
*.spec
36+
37+
# Installer logs
38+
pip-log.txt
39+
pip-delete-this-directory.txt
40+
41+
# Unit test / coverage reports
42+
htmlcov/
43+
.tox/
44+
.nox/
45+
.coverage
46+
.coverage.*
47+
.cache
48+
nosetests.xml
49+
coverage.xml
50+
*.cover
51+
*.py,cover
52+
.hypothesis/
53+
.pytest_cache/
54+
55+
# Translations
56+
*.mo
57+
*.pot
58+
59+
# Django stuff:
60+
*.log
61+
local_settings.py
62+
db.sqlite3
63+
db.sqlite3-journal
64+
65+
# Flask stuff:
66+
instance/
67+
.webassets-cache
68+
69+
# Scrapy stuff:
70+
.scrapy
71+
72+
# Sphinx documentation
73+
docs/_build/
74+
75+
# PyBuilder
76+
target/
77+
78+
# Jupyter Notebook
79+
.ipynb_checkpoints
80+
81+
# IPython
82+
profile_default/
83+
ipython_config.py
84+
85+
# pyenv
86+
.python-version
87+
88+
# pipenv
89+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
90+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
91+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
92+
# install all needed dependencies.
93+
#Pipfile.lock
94+
95+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
96+
__pypackages__/
97+
98+
# Celery stuff
99+
celerybeat-schedule
100+
celerybeat.pid
101+
102+
# SageMath parsed files
103+
*.sage.py
104+
105+
# Environments
106+
.env
107+
.venv
108+
env/
109+
venv/
110+
ENV/
111+
env.bak/
112+
venv.bak/
113+
114+
# Spyder project settings
115+
.spyderproject
116+
.spyproject
117+
118+
# Rope project settings
119+
.ropeproject
120+
121+
# mkdocs documentation
122+
/site
123+
124+
# mypy
125+
.mypy_cache/
126+
.dmypy.json
127+
dmypy.json
128+
129+
# Pyre type checker
130+
.pyre/
131+
132+
133+
# VSCode extension
134+
.vscode/
135+
/.favorites.json
136+
137+
# TypeScript incremental build states
138+
*.tsbuildinfo
139+
140+
# Local state files & OS specifics
141+
.DS_Store
142+
node_modules/
143+
lerna-debug.log
144+
dist/
145+
pack/
146+
.BUILD_COMPLETED
147+
.local-npm/
148+
.tools/
149+
coverage/
150+
.nyc_output
151+
.LAST_BUILD
152+
*.sw[a-z]
153+
*~
154+
.idea
155+
156+
# We don't want tsconfig at the root
157+
/tsconfig.json
158+
159+
# CDK Context & Staging files
160+
cdk.context.json
161+
.cdk.staging/
162+
cdk.out/
163+
164+
165+
########################
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
# Amazon API Gateway HTTP API to Amazon EventBridge
2+
3+
This pattern creates an HTTP API endpoint that directly integrates with Amazon EventBridge
4+
5+
Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/apigw-http-api-eventbridge-python
6+
7+
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. You are responsible for any AWS costs incurred. No warranty is implied in this example.
8+
9+
## Requirements
10+
11+
- [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.
12+
- [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
13+
- [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
14+
- [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed
15+
16+
## Deployment Instructions
17+
18+
1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
19+
```
20+
git clone https://github.com/aws-samples/serverless-patterns
21+
```
22+
2. Change directory to the pattern directory:
23+
```
24+
cd serverless-patterns/apigw-http-api-eventbridge-python
25+
```
26+
3. Create a virtual environment for Python:
27+
```
28+
python3 -m venv .venv
29+
```
30+
4. Activate the virtual environment
31+
```
32+
source .venv/bin/activate
33+
```
34+
For a Windows platform, activate the virtualenv like this:
35+
```
36+
.venv\Scripts\activate.bat
37+
```
38+
5. Install the Python required dependencies:
39+
```
40+
pip install -r requirements.txt
41+
```
42+
6. Review the CloudFormation template the cdk generates for you stack using the following AWS CDK CLI command:
43+
```
44+
cdk synth
45+
```
46+
7. From the command line, use AWS CDK to deploy the AWS resources for the serverless application as specified in the app.py file:
47+
```
48+
cdk deploy
49+
```
50+
8. Note the outputs from the CDK deployment process. These contain the API Gateway ID which is used for testing.
51+
52+
## How it works
53+
54+
This pattern creates an Amazon API gateway HTTP API endpoint. The endpoint uses service integrations to directly connect to Amazon EventBridge.
55+
56+
## Testing
57+
58+
To test the endpoint first send data using the following command. Be sure to update the endpoint with endpoint of your stack.
59+
60+
```
61+
curl --location --request POST '<your api endpoint>' --header 'Content-Type: application/json' \
62+
--data-raw '{
63+
"Detail":{
64+
"message": "This is my test"
65+
}
66+
}'
67+
```
68+
69+
If everything works as expected EventBridge will return the result of sending the message operation and APIGateway will proxy the payload to the client application. The payload should looks like something like the following payload:
70+
71+
```
72+
{
73+
"Entries": [
74+
{
75+
"EventId": "{UNIQUE_UUID}"
76+
}
77+
],
78+
"FailedEntryCount": 0 // <- This indicates that the message was successfully sent
79+
}
80+
```
81+
82+
## Cleanup
83+
84+
Run the given command to delete the resources that were created. It might take some time for the CloudFormation stack to get deleted.
85+
86+
```
87+
cdk destroy
88+
```
89+
90+
---
91+
92+
Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
93+
94+
SPDX-License-Identifier: MIT-0

apigw-http-api-eventbridge-python/apigw_http_api_eventbridge/__init__.py

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
from aws_cdk import (
2+
Stack,
3+
aws_events as events,
4+
aws_logs as logs,
5+
aws_events_targets as cloudw,
6+
aws_apigatewayv2_alpha as apigw,
7+
CfnOutput
8+
)
9+
from aws_cdk.aws_apigateway import (
10+
IntegrationType
11+
)
12+
from aws_cdk.aws_apigatewayv2 import (
13+
CfnIntegration,
14+
CfnRoute,
15+
)
16+
from aws_cdk.aws_iam import (
17+
Role,
18+
ServicePrincipal,
19+
PolicyStatement,
20+
Effect
21+
)
22+
from constructs import Construct
23+
24+
25+
class ApigwHttpApiEventbridgeStack(Stack):
26+
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
27+
super().__init__(scope, construct_id, **kwargs)
28+
29+
# Creating an event bus. Change `event_bus_name` with your own name
30+
event_bus = events.EventBus(
31+
scope=self,
32+
id='MyEventBus',
33+
event_bus_name='MyEventBus'
34+
)
35+
36+
# Match the events to log to certain region
37+
event_logger_rule = events.Rule(
38+
scope=self,
39+
id="EventLoggerRule",
40+
description="Log all events",
41+
event_pattern=events.EventPattern(
42+
region=['app-southeast-2']
43+
),
44+
event_bus=event_bus
45+
)
46+
47+
# Creating log group
48+
log_group = logs.LogGroup(
49+
scope=self,
50+
id='EventLogGroup',
51+
log_group_name=f'/aws/events/{event_bus.event_bus_name}'
52+
)
53+
54+
event_logger_rule.add_target(
55+
cloudw.CloudWatchLogGroup(log_group=log_group)
56+
)
57+
58+
# Creating the HTTP Api. Change `api_name` with your own name
59+
http_api = apigw.HttpApi(
60+
scope=self,
61+
id='MyRestApi',
62+
api_name='MyRestApi'
63+
)
64+
65+
api_role = Role(
66+
scope=self,
67+
id='EventBridgeIntegrationRole',
68+
assumed_by=ServicePrincipal('apigateway.amazonaws.com')
69+
)
70+
71+
api_role.add_to_policy(
72+
PolicyStatement(
73+
effect=Effect.ALLOW,
74+
resources=[event_bus.event_bus_arn],
75+
actions=['events:PutEvents']
76+
)
77+
)
78+
79+
event_bridge_integration = CfnIntegration(
80+
scope=self,
81+
id='EventBridgeIntegration',
82+
integration_type=str(IntegrationType.AWS_PROXY),
83+
integration_subtype='EventBridge-PutEvents',
84+
credentials_arn=api_role.role_arn,
85+
api_id=http_api.http_api_id,
86+
request_parameters={
87+
'Source': 'WebApp',
88+
'DetailType': 'MyDetailType',
89+
'Detail': '$request.body',
90+
'EventBusName': event_bus.event_bus_arn
91+
},
92+
payload_format_version='1.0',
93+
timeout_in_millis=10000
94+
)
95+
96+
CfnRoute(
97+
scope=self,
98+
id='EventRoute',
99+
api_id=http_api.http_api_id,
100+
route_key='POST /',
101+
target=f'integrations/{event_bridge_integration.ref}'
102+
)
103+
104+
CfnOutput(
105+
scope=self,
106+
id='apiUrl',
107+
value=http_api.url,
108+
description='HTTP API endpoint URL'
109+
)

0 commit comments

Comments
 (0)