Setting up an AWS EventBridge integration to receive real-time Genesys Cloud events
What You Will Build
- A Python script that configures a Genesys Cloud Integration to stream real-time conversation events to an AWS EventBridge HTTP Endpoint.
- This tutorial uses the Genesys Cloud v2 REST API via the
genesys-cloud-pythonSDK to create, configure, and test the integration. - The programming language covered is Python 3.9+.
Prerequisites
- OAuth Client Type: Service Account (Client Credentials) or User Account (Authorization Code with PKCE).
- Required Scopes:
integration:write(to create/update the integration)integration:read(to query existing integrations)integration:events:write(to configure event streams)integration:events:read(to read event configurations)integration:events:test(to trigger test events)
- SDK Version:
genesys-cloud-python>= 160.0.0 (Ensure you are using a version compatible with the current API spec). - Runtime: Python 3.9 or higher.
- Dependencies:
genesys-cloud-pythonboto3(optional, for verifying EventBridge side, but not required for Genesys configuration)python-dotenv(for secure credential management)
Authentication Setup
Genesys Cloud uses OAuth 2.0. For server-side integrations like this, the Client Credentials flow is standard. You must generate a Service Account in the Genesys Cloud Admin Console with the scopes listed above.
Create a .env file in your project root:
GENESYS_CLIENT_ID=your_client_id_here
GENESYS_CLIENT_SECRET=your_client_secret_here
GENESYS_REGION=us-east-1 # or your specific region
Initialize the SDK client. The PureCloudPlatformClientV2 handles token acquisition and refresh automatically.
import os
from dotenv import load_dotenv
from purecloudplatformclientv2 import (
Configuration,
ApiClient,
PlatformApi,
IntegrationApi
)
from purecloudplatformclientv2.rest import ApiException
# Load environment variables
load_dotenv()
def get_genesys_client() -> ApiClient:
"""
Initializes and returns an authenticated Genesys Cloud API Client.
"""
configuration = Configuration(
client_id=os.getenv('GENESYS_CLIENT_ID'),
client_secret=os.getenv('GENESYS_CLIENT_SECRET'),
host=os.getenv('GENESYS_REGION', 'us-east-1')
)
# The ApiClient handles OAuth token management internally
api_client = ApiClient(configuration)
return api_client
# Instantiate the specific API wrapper for Integrations
def get_integration_api(api_client: ApiClient) -> IntegrationApi:
return IntegrationApi(api_client)
Implementation
Step 1: Create the Integration Entity
Before configuring events, you must create the Integration entity itself. This entity represents the connection between Genesys Cloud and AWS EventBridge.
Key parameters:
- name: A unique identifier for your integration.
- type: Must be
aws.eventbridgefor this specific integration. - description: Optional, but recommended for auditing.
from purecloudplatformclientv2 import CreateIntegrationRequest
def create_integration(integration_api: IntegrationApi, integration_name: str) -> str:
"""
Creates a new Genesys Cloud Integration of type 'aws.eventbridge'.
Returns the integration ID.
"""
body = CreateIntegrationRequest(
name=integration_name,
type="aws.eventbridge",
description="Real-time event stream to AWS EventBridge"
)
try:
# POST /api/v2/integrations
response = integration_api.post_integrations(body=body)
print(f"Integration created successfully. ID: {response.id}")
return response.id
except ApiException as e:
if e.status == 409:
print("Integration with this name already exists. Please use a unique name or query existing ones.")
else:
raise e
# Example Usage
# integration_id = create_integration(integration_api, "MyEventBridgeStream")
Expected Response (201 Created):
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"name": "MyEventBridgeStream",
"type": "aws.eventbridge",
"description": "Real-time event stream to AWS EventBridge",
"active": false,
"enabled": false,
"createdBy": { ... },
"createdTime": "2023-10-27T10:00:00.000Z",
"updatedBy": { ... },
"updatedTime": "2023-10-27T10:00:00.000Z"
}
Step 2: Configure EventBridge Specific Settings
The aws.eventbridge integration type requires specific configuration properties to establish the secure connection to AWS. You must provide the EventBridge HTTP Endpoint URL and the AWS Signature credentials.
Note: Genesys Cloud signs requests using AWS Signature Version 4. You need an IAM User with permissions to put events to EventBridge.
Required Configuration Properties:
endpoint: The HTTPS URL of your EventBridge HTTP Endpoint.aws_access_key_id: The Access Key ID.aws_secret_access_key: The Secret Access Key.aws_region: The AWS region where the endpoint resides.
from purecloudplatformclientv2 import UpdateIntegrationRequest
def configure_integration_settings(
integration_api: IntegrationApi,
integration_id: str,
endpoint_url: str,
aws_access_key: str,
aws_secret_key: str,
aws_region: str
) -> None:
"""
Updates the integration with AWS EventBridge specific connection details.
"""
# The configuration object is a dictionary of string key-value pairs
config = {
"endpoint": endpoint_url,
"aws_access_key_id": aws_access_key,
"aws_secret_access_key": aws_secret_key,
"aws_region": aws_region
}
body = UpdateIntegrationRequest(
configuration=config
)
try:
# PUT /api/v2/integrations/{integrationId}
integration_api.put_integration_integration_id(
integration_id=integration_id,
body=body
)
print(f"Integration {integration_id} configured with EventBridge settings.")
except ApiException as e:
print(f"Failed to configure integration: {e.body}")
raise
Security Warning: Never hardcode AWS credentials. Use environment variables or a secrets manager. The aws_secret_access_key is stored encrypted by Genesys Cloud.
Step 3: Define and Enable Event Streams
Creating the integration and configuring credentials does not start sending data. You must define which events to stream and enable the stream.
Genesys Cloud supports various event types (e.g., conversation.analyzed, conversation.message.created, agent.available). For this example, we will stream conversation.message.created events.
You must also map the Genesys event fields to the EventBridge payload structure. Genesys Cloud provides a default mapping for EventBridge, but you can customize it.
from purecloudplatformclientv2 import (
PostIntegrationStreamRequest,
StreamFilter,
StreamFilterCondition
)
def create_event_stream(
integration_api: IntegrationApi,
integration_id: str,
event_type: str = "conversation.message.created"
) -> str:
"""
Creates an event stream for the integration.
Returns the stream ID.
"""
# Define the filter to select which events to send
# In this example, we send all events of the specified type
filter_conditions = [
StreamFilterCondition(
type="eventType",
value=event_type
)
]
stream_filter = StreamFilter(
conditions=filter_conditions
)
body = PostIntegrationStreamRequest(
filter=stream_filter,
enabled=True, # Enable the stream immediately
name=f"Stream for {event_type}"
)
try:
# POST /api/v2/integrations/{integrationId}/streams
response = integration_api.post_integration_streams(
integration_id=integration_id,
body=body
)
print(f"Event stream created. Stream ID: {response.id}")
return response.id
except ApiException as e:
print(f"Failed to create event stream: {e.body}")
raise
Step 4: Verify and Test the Integration
Before relying on production data, test the integration. Genesys Cloud provides a test method that sends a synthetic event to your configured endpoint.
def test_integration(integration_api: IntegrationApi, integration_id: str) -> None:
"""
Triggers a test event to verify the connection to AWS EventBridge.
"""
try:
# POST /api/v2/integrations/{integrationId}/test
response = integration_api.post_integration_test(
integration_id=integration_id
)
# The response object contains details about the test attempt
print("Test event sent successfully.")
print(f"Response: {response}")
# Note: The response is often empty or minimal.
# You must check AWS EventBridge CloudWatch Logs or your target service
# to confirm receipt.
except ApiException as e:
if e.status == 400:
print("Bad Request: Check your EventBridge endpoint URL and AWS credentials.")
elif e.status == 502 or e.status == 503:
print("Connection Error: Genesys Cloud could not reach the EventBridge endpoint.")
else:
raise e
Complete Working Example
This script combines all steps into a single executable workflow. It assumes you have already created the AWS EventBridge HTTP Endpoint and IAM User.
import os
import sys
from dotenv import load_dotenv
from purecloudplatformclientv2 import (
Configuration,
ApiClient,
IntegrationApi,
CreateIntegrationRequest,
UpdateIntegrationRequest,
PostIntegrationStreamRequest,
StreamFilter,
StreamFilterCondition
)
from purecloudplatformclientv2.rest import ApiException
def load_config():
load_dotenv()
return {
'client_id': os.getenv('GENESYS_CLIENT_ID'),
'client_secret': os.getenv('GENESYS_CLIENT_SECRET'),
'region': os.getenv('GENESYS_REGION', 'us-east-1'),
'aws_endpoint': os.getenv('AWS_EVENTBRIDGE_ENDPOINT'),
'aws_access_key': os.getenv('AWS_ACCESS_KEY_ID'),
'aws_secret_key': os.getenv('AWS_SECRET_ACCESS_KEY'),
'aws_region': os.getenv('AWS_REGION', 'us-east-1')
}
def main():
config = load_config()
# Validate required configs
required_keys = ['client_id', 'client_secret', 'aws_endpoint', 'aws_access_key', 'aws_secret_key']
for key in required_keys:
if not config[key]:
raise ValueError(f"Missing required environment variable: {key.upper()}")
# 1. Initialize Client
configuration = Configuration(
client_id=config['client_id'],
client_secret=config['client_secret'],
host=config['region']
)
api_client = ApiClient(configuration)
integration_api = IntegrationApi(api_client)
integration_name = "DevEventBridgeStream"
event_type = "conversation.message.created"
try:
# 2. Create Integration
print(f"Creating integration: {integration_name}")
create_req = CreateIntegrationRequest(
name=integration_name,
type="aws.eventbridge",
description="Dev stream to EventBridge"
)
integration_resp = integration_api.post_integrations(body=create_req)
integration_id = integration_resp.id
print(f"Integration ID: {integration_id}")
# 3. Configure AWS Settings
print("Configuring AWS EventBridge settings...")
update_req = UpdateIntegrationRequest(
configuration={
"endpoint": config['aws_endpoint'],
"aws_access_key_id": config['aws_access_key'],
"aws_secret_access_key": config['aws_secret_key'],
"aws_region": config['aws_region']
}
)
integration_api.put_integration_integration_id(
integration_id=integration_id,
body=update_req
)
print("Settings configured.")
# 4. Create Event Stream
print(f"Creating stream for event type: {event_type}")
filter_cond = StreamFilterCondition(
type="eventType",
value=event_type
)
stream_filter = StreamFilter(conditions=[filter_cond])
stream_req = PostIntegrationStreamRequest(
filter=stream_filter,
enabled=True,
name=f"Stream-{event_type}"
)
stream_resp = integration_api.post_integration_streams(
integration_id=integration_id,
body=stream_req
)
print(f"Stream ID: {stream_resp.id}")
# 5. Test Integration
print("Testing integration...")
integration_api.post_integration_test(integration_id=integration_id)
print("Test event sent. Check AWS CloudWatch Logs for confirmation.")
except ApiException as e:
print(f"Genesys API Error: {e.status} - {e.reason}")
print(f"Body: {e.body}")
sys.exit(1)
except Exception as e:
print(f"Unexpected Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
Common Errors & Debugging
Error: 401 Unauthorized
- Cause: Invalid Client ID/Secret or expired token.
- Fix: Verify the Service Account credentials in Genesys Cloud Admin. Ensure the client secret is copied correctly without trailing spaces.
Error: 403 Forbidden
- Cause: The Service Account lacks the required scopes.
- Fix: Navigate to Admin > Security > Service Accounts. Edit the account and ensure
integration:write,integration:events:write, andintegration:events:testare checked.
Error: 400 Bad Request (Configuration)
- Cause: Invalid EventBridge Endpoint URL or malformed AWS credentials.
- Fix: Ensure the endpoint URL starts with
https://. Verify the AWS Access Key and Secret Key are valid and belong to a user withevents:PutEventspermission on the target event bus.
Error: 502/503 Bad Gateway (Test Failure)
- Cause: Genesys Cloud cannot reach the EventBridge endpoint.
- Fix:
- Check if the EventBridge endpoint is public or requires VPC access. Genesys Cloud originates requests from public IPs.
- Verify the AWS Security Group associated with the endpoint allows inbound traffic on port 443 from Genesys Cloud IP ranges.
- Check AWS CloudTrail for denied requests.
Error: Stream Not Sending Data
- Cause: The event filter is too restrictive or the event type is incorrect.
- Fix: Query existing integrations to check stream status. Ensure the
eventTypematches exactly with Genesys Cloud’s event schema (e.g.,conversation.message.createdvsmessage.created).