Package: ibm-eventnotifications
IBM Cloud Event Notifications Python Admin SDK 0.3.0Python client library to interact with variousIBM Cloud Event Notifications APIs.Table of ContentsOverviewPrerequisitesInstallationInitialize SDKUsing the SDKSet EnvironmentQuestionsIssuesOpen source @ IBMContributingLicenseOverviewThe IBM Cloud Event Notifications Python SDK allows developers to programmatically interact with Event Notifications service in IBM cloud.Service NameModule NameImported Class NameEvent Notifications Serviceibm_eventnotificationsEventNotificationsV1PrerequisitesAnIBM Cloudaccount.An Event Notifications InstancePython 3.6 or above.InstallationTo install, use pip or easy_install:pipinstall--upgrade"ibm_eventnotifications>=0.3.0"oreasy_install--upgrade"ibm_eventnotifications>=0.3.0"Initialize SDKInitialize the sdk to connect with your Event Notifications service instance.fromibm_eventnotifications.event_notifications_v1importEventNotificationsV1fromibm_cloud_sdk_core.authenticatorsimportIAMAuthenticator# Create an IAM authenticator.authenticator=IAMAuthenticator('<iam-api-key>')# Construct the service client.event_notifications_service=EventNotificationsV1(authenticator=authenticator)# Set our custom service URL (optional)event_notifications_service.set_service_url('https://'+region+'.event-notifications.cloud.ibm.com/event-notifications')To configure service URL for Private EndpointIf you enabled service endpoints in your account, you can send API requests over the IBM Cloud private network. In the initialisation, the base endpoint URLs of the IAM(authenticator) & Event Notification(service) should be modified to point to private endpoints.Setting client options programmatically# Create an IAM authenticator.authenticator=IAMAuthenticator('<iam-api-key>','https://private.iam.cloud.ibm.com')# Construct the service client.event_notifications_service=EventNotificationsV1(authenticator=authenticator)# To configure service URL for Private Endpointevent_notifications_service.set_service_url('https://private.'+region+'.event-notifications.cloud.ibm.com/event-notifications')Using external configuration propertiesEVENT_NOTIFICATIONS_AUTH_URL=https://private.iam.cloud.ibm.com/identity/tokenregion : Region of the Event Notifications InstanceUsing the SDKSDK Methods to consumeSourceCreate SourceList SourcesGet SourceUpdate SourceDelete SourceTopicsCreate TopicsList TopicsGet TopicUpdate TopicsDelete TopicsDestinationsCreate DestinationList DestinationsGet DestinationUpdate DestinationDelete DestinationCustom Domain_Name_verificationTest DestinationTemplatesCreate TemplateList TemplatesGet TemplateUpdate TemplateDelete TemplatePush Destination APIsCreate Destination tag subscriptionList Destination tag subscriptionDelete Destination device tag subscriptionSubscriptionsCreate SubscriptionList SubscriptionsGet SubscriptionUpdate SubscriptionDelete SubscriptionIntegrationCreate IntegrationList IntegrationsGet IntegrationsUpdate IntegrationSend NotificationsSourceCreate Sourcesource_response=event_notifications_service.create_sources(<instance-id>,# Event notifications service instance GUIDname=<source-name>,description=<source-description>,enabled=False).get_result()print(json.dumps(source_response,indent=2))List Sourcessource_list=event_notifications_service.list_sources(<instance-id>,# Event notifications service instance GUID).get_result()print(json.dumps(source_list,indent=2))Get Sourcesource=event_notifications_service.get_source(<instance-id>,# Event notifications service instance GUIDid=<source-id>,# Event notifications service instance Source ID).get_result()print(json.dumps(source,indent=2))Update Sourcesource=event_notifications_service.update_source(<instance-id>,# Event notifications service instance GUIDid=<source-id>,# Event notifications service instance Source IDname=<source-name>,description=<source-description>,enabled=True).get_result()print(json.dumps(source,indent=2))Delete Sourceresponse=event_notifications_service.delete_source(<instance-id>,# Event notifications service instance GUIDid=<source-id>,# Event notifications service instance Source ID)TopicsCreate Topicrules_model={'enabled':False,'event_type_filter':'$.notification_event_info.event_type ==\'cert_manager\'',#Add your event type filter here.'notification_filter':'$.notification.findings[0].severity ==\'MODERATE\'',#Add your notification filter here.}# Construct a dict representation of a TopicUpdateSourcesItem modeltopic_update_sources_item_model={'id':<source_id>,'rules':[rules_model],}topic_response=event_notifications_service.create_topic(<instance_id>,name=<topic-name>,description=<topic-description>,sources=[topic_update_sources_item_model])print(json.dumps(topic_response,indent=2))List Topicstopic_list=event_notifications_service.list_topics(<instance-id>,).get_result()print(json.dumps(topic_list,indent=2))Get Topictopic=event_notifications_service.get_topic(<instance-id>,# Event notifications service instance GUIDid=<topic-id>,# Event notifications service instance Topic ID).get_result()print(json.dumps(topic,indent=2))Update Topicrules_model={'enabled':True,'event_type_filter':'$.notification_event_info.event_type ==\'core_cert_manager\'','notification_filter':'$.notification.findings[0].severity ==\'SEVERE\'',}# Construct a dict representation of a TopicUpdateSourcesItem modeltopic_update_sources_item_model={'id':<source-id>,# Event notifications service instance Source ID'rules':[rules_model],}description="Updated Topic for GCM notifications"name='Updated Admin Topic Compliance'topic=event_notifications_service.replace_topic(<instance-id>,# Event notifications service instance GUIDid=<topic-id>,# Event notifications service instance Topic IDname=<topic-update-name># Event notifications service instance Topic Namedescription=<topic-update-description># Event notifications service instance Topic descriptionsources=[topic_update_sources_item_model])print(json.dumps(topic,indent=2))rulesModel:=&eventnotificationsv1.Rules{Enabled:core.BoolPtr(true),EventTypeFilter:core.StringPtr("$.notification_event_info.event_type == 'core_cert_manager'"),# Add your event type filter here.NotificationFilter:core.StringPtr("$.notification.findings[0].severity == 'SEVERE'"),# Add your notification filter here.}Delete Topicresponse=event_notifications_service.delete_topic(<instance-id>,id=<topic-id>,)DestinationsCreate Destinationdestination_config_params_model={'url':'<destination-config-url>','verb':'<destination-config-verb>','custom_headers':{'<header-key>':'<header-value>',},'sensitive_headers':['<header-key>'],}# Construct a dict representation of a DestinationConfig modeldestination_config_model={'params':destination_config_params_model,}destination=event_notifications_service.create_destination(<instance-id>,<destination-name>,type=<destination-type>,description=description,config=destination_config_model).get_result()print(json.dumps(destination,indent=2))Among the supported destinations, if you need to create Push Notification destinations, you have the additional option of choosing a destination of production type or pre-production type.
Setpre_prodboolean parameter totrueto configure destination as pre-production destination else set the value asfalse.
Supported destinations are Android, iOS, Chrome, Firefox, and Safari.List Destinationsdestination_list=event_notifications_service.list_destinations(<instance-id>,).get_result()print(json.dumps(destination_list,indent=2))Get Destinationdestination=event_notifications_service.get_destination(<instance-id>,# Event notifications service instance GUIDid=<destination-id>,# Event notifications service instance Destination ID).get_result()print(json.dumps(destination,indent=2))Update Destination# Construct a dict representation of a DestinationConfigParamsWebhookDestinationConfig modeldestination_config_params_model={'url':'<destination-config-update-url>','verb':'<destination-config-update-verb>','sensitive_headers':['<header-key>'],}# Construct a dict representation of a DestinationConfig modeldestination_config_model={'params':destination_config_params_model,}destination=event_notifications_service.update_destination(<instance-id>,# Event notifications service instance GUIDid=<destination-id>,# Event notifications service instance Destination IDname=<destination-update-name>,description=<destination-update-description>,config=destination_config_model).get_result()print(json.dumps(destination,indent=2))Delete Destinationresponse=event_notifications_service.delete_destination(<instance-id>,# Event notifications service instance GUIDid=<destination-id>,# Event notifications service instance Destination ID)Test DestinationThis functionality allows you to test a destination. The feature simplifies the process of verifying whether a destination is functioning correctly.
Currently, this functionality supports following destinations:SlackPagerDutyServiceNowMicrosoft® TeamsIBM Cloud Code EngineIBM Cloud FunctionsIBM Cloud Object Storagetest_destination_response=event_notifications_service.test_destination(<instance-id>,id=<destination-id>)Once the test is completed, you will be presented with the results. These results will typically include:Status: Whether the test is successful or failedResponse Code: If test fails, then the response code sent from the end destination client is returnedResponse Message: If test fails, then the response message sent from the end destination client is returnedCustom Domain Name VerificationAfter creation of the custom email destination with your domain name, make sure its validated for the right ownership.
This can be done with SPF and DKIM verification.Sender Policy Framework (SPF), which is used to authenticate the sender of an email. SPF specifies the mail servers that are allowed to send email for your domain.DomainKeys Identified Mail (DKIM), which allows an organization to take responsibility for transmitting a message by signing it. DKIM allows
the receiver to check the email that claimed to have come from a specific domain, is authorized by the owner of that domain.verification_response=event_notifications_service.update_verify_destination(<instance-id>,# Event notifications service instance GUIDid=<destination-id>,# Event notifications service instance Destination IDtype=<verification-type>,# verification type spf/dkim).get_result()TemplatesTemplate is a pre-defined layout, that may include content like images, text and dynamic content based on event. Rather than creating a new content from scratch each time, you can use a template as a base and configure them in subscription.
supports the following templates:Custom Email notificationCustom Email invitationCreate Templatetemplate_config_model={'body':'base 64 encoded html content','subject':'Hi this is invitation for invitation message',}create_template_response=event_notifications_service.create_template(instance_id=<instance-id>,name=<template-name>,type=<template-type>,params=template_config_model,description=<template-description>).get_result()List Templateslist_templates_response=event_notifications_service.list_templates(instance_id=<instance-id>,limit=<limit>,offset=<offset>,search=<search>)templates_list=list_templates_response.get_result()Get Templateget_template_response=event_notifications_service.get_template(instance_id=<instance-id>,id=<template_id>).get_result()Update Templatetemplate_config_model={'body':'base 64 encode html content','subject':'Hi this is invitation for invitation message',}replace_template_response=event_notifications_service.replace_template(instance_id=<instance-id>,id=<template_id>name=<template_name>,type=<template-type>,description=<template-description>,params=template_config_model).get_result()Delete Templatedelete_template_response=event_notifications_service.delete_template(instance_id=<instance-id>,id=<template_id>).get_result()Push Destination APIsCreate Destination tag subscriptiontag_subscription=_event_notifications_service.create_tags_subscription(<instance-id>,# Event notifications service instance GUID<destination-id>,# Event notifications service Destintaion ID<device_id>,# Event notifications service Device ID<tag_name># Event notifications service Tag Name).get_result()print(json.dumps(tag_subscription,indent=2))List Destination tag subscriptionsubscription=_event_notifications_service.list_tags_subscription(<instance-id>,# Event notifications service instance GUID<destination-id># Event notifications service Destintaion ID).get_result()print(json.dumps(subscription,indent=2))Delete Destination device tag subscriptionresponse=_event_notifications_service.delete_tags_subscription(<instance-id>,# Event notifications service instance GUID<destination-id>,# Event notifications service Destintaion ID<device_id>,# Event notifications service Device ID<tag_name># Event notifications service Tag Name).get_result()print(json.dumps(response,indent=2))SubscriptionsCreate Subscription#`While Creating Subscription use any of one option from webhook, or email`subscription_create_attributes_model={'signing_enabled':False,}subscription=event_notifications_service.create_subscription(<instance-id>,# Event notifications service instance GUIDname,<destination-id>,# Event notifications service instance Destination ID<topic-id># Event notifications service instance Topic IDattributes=subscription_create_attributes_model,description=<subscription-description>).get_result()print(json.dumps(subscription,indent=2))List Subscriptionssubscription_list=event_notifications_service.list_subscriptions(<instance-id>,# Event notifications service instance GUID).get_result()print(json.dumps(subscription_list,indent=2))Get Subscriptionsubscription=event_notifications_service.get_subscription(<instance-id>,# Event notifications service instance GUIDid=<subscription-id>,# Event notifications service instance Subscription ID).get_result()print(json.dumps(subscription,indent=2))Update Subscriptionsubscription_update_attributes_model={'signing_enabled':True,}subscription=event_notifications_service.update_subscription(<instance-id>,# Event notifications service instance GUIDid=<subscription-id>,# Event notifications service instance Subscription IDname=<subscription-update-name>,description=<subscription-update-description>,attributes=subscription_update_attributes_model).get_result()print(json.dumps(subscription,indent=2))Delete Subscriptionresponse=event_notifications_service.delete_subscription(<instance-id>,# Event notifications service instance GUIDid=<subscription-id>,# Event notifications service instance Subscriptions ID)IntegrationCreate Integrationintegration_metadata={"endpoint":cos_end_point,"crn":cos_instance_crn,"bucket_name":cos_bucket_name,}create_integration_response=self.event_notifications_service.create_integration(instance_id,type="collect_failed_events",metadata=integration_metadata,)integration_response=create_integration_response.get_result()List Integrationslist_integrations_response=event_notifications_service.list_integrations(<instance-id>,<limit>,<offset>,<search>,)integration_response=list_integrations_response.get_result()Get Integrationget_integration_response=event_notifications_service.get_integration(<instance_id>,id=<integration_id>)integration_response=get_integration_response.get_result()Update IntegrationFor kms/hs-cryptointegration_metadata={'endpoint':'<end-point>','crn':'<crn>','root_key_id':'<root-key-id>'}update_integration_response=event_notifications_service.replace_integration(<instance_id>,type="kms/hs-crypto",id=<integration_id>,metadata=integration_metadata)integration_response=update_integration_response.get_result()For Cloud Object Storageintegration_metadata={'endpoint':'<end-point>','crn':'<crn>','bucket-name':'<cos-bucket-name>'}update_integration_response=event_notifications_service.replace_integration(<instance_id>,type="collect_failed_events",id=<integration_id>,metadata=integration_metadata)integration_response=update_integration_response.get_result()Send Notificationsnotification_devices_model={'fcm_devices':['<fcm-device-ids>'],'apns_devices':['<apns-device-ids>'],'user_ids':['<user-ids>'],'tags':['<tag-names>'],'platforms':['<device-platforms>'],}notification_apns_body_model={"aps":{"alert":"<notification-message>","badge":5,},}notification_fcm_body_model={'message':{'android':{'notification':{'title':'<notification-title>','body':'<notification-message>',},'data':{'name':'Robert','description':'notification for the Poker',},},},}message_apns_headers={"apns-collapse-id":"<apns-apns-collapse-id-value>",}notificationSafariBodymodel={'saf':{'alert':'Game Request','badge':5,},}notification_id="<notification-id>"notification_severity="<notification-severity>"type_value="<notification-type>"notifications_source="<notification-source>"htmlbody='"Hi  ,<br/>Certificate expiring in 90 days.<br/><br/>Please login to '\'<a href="https: //cloud.ibm.com/security-compliance/dashboard">'\'Security and Complaince dashboard</a> to find more information<br/>"'mailto='[\"abc@ibm.com\",\"def@us.ibm.com\"]'smsto='[\"+911234567890\",\"+911224567890\"]'notification_create_model={'ibmenseverity':notification_severity,'ibmenfcmbody':json.dumps(notification_fcm_body_model),'ibmenpushto':json.dumps(notification_devices_model),'ibmenapnsbody':json.dumps(notification_apns_body_model),'ibmensourceid':source_id,'ibmendefaultshort':'short info','ibmendefaultlong':'long info','ibmensafaribody':json.dumps(notificationSafariBodymodel),'ibmenhtmlbody':htmlbody,'ibmensubject':'Findings on IBM Cloud Security Advisor','ibmenmailto':mailto,'ibmensmsto':smsto,'id':notification_id,'source':notifications_source,'type':type_value,'specversion':'1.0','time':'2019-01-01T12:00:00.000Z',}send_notifications_response=event_notifications_service.send_notifications(instance_id,body=notification_create_model).get_result()Send Notifications Variablesibmenpushto- Set up the push notifications targets.user_ids(Array of String) - Send notification to the specified userIds.fcm_devices(Array of String) - Send notification to the list of specified Android devices.apns_devices(Array of String) - Send notification to the list of specified iOS devices.chrome_devices(Array of String) - Send notification to the list of specified Chrome devices.firefox_devices(Array of string) - Send notification to the list of specified Firefox devices.tags(Array of string) - Send notification to the devices that have subscribed to any of these tags.platforms(Array of string) - Send notification to the devices of the specified platforms.Pass 'G' for google (Android) devices.Pass 'A' for iOS devices.Pass 'WEB_FIREFOX' for Firefox browser.Pass 'WEB_CHROME' for Chrome browser.Event Notifications SendNotificationsOptions- Event Notifications Send Notifications method.instance_id(string) - Unique identifier for IBM Cloud Event Notifications instance.ibmenseverity(string) - Severity for the notifications. Some sources can have the concept of an Event severity. Hence a handy way is provided to specify a severity of the event. example: LOW, HIGH, MEDIUMid* (string) - A unique identifier that identifies each event. source+id must be unique. The backend should be able to uniquely track this id in logs and other records. Send unique ID for each send notification. Same ID can be sent in case of failure of send notification. source+id will be logged in IBM Cloud Logging service. Using this combination we will be able to trace the event movement from one system to another and will aid in debugging and tracing.source* (string) - Source of the notifications. This is the identifier of the event producer. A way to uniquely identify the source of the event. For IBM Cloud services this is the crn of the service instance producing the events. For API sources this can be something the event producer backend can uniquely identify itself with.ibmensourceid* (string) - This is the ID of the source created in EN. This is available in the EN UI in the "Sources" section.type(string) - This describes the type of event. It is of the form : This type is defined by the producer. The event type name has to be prefixed with the reverse DNS names so the event type is uniquely identified. The same event type can be produced by 2 different sources. It is highly recommended to use hyphen - as a separator instead of _.data(string) - The payload for webhook notification. If data is added as part of payload then its mandatory to adddatacontenttype.datacontenttype- The notification content type. example: application/jsontime(string) - Time of the notifications. UTC time stamp when the event occurred. Must be in the RFC 3339 format.ibmenpushto(string) - Targets for the FCM notifications. This contains details about the destination where you want to send push notification. This attribute is mandatory for successful delivery from an Android FCM or APNS destination.ibmenfcmbody(string) - Set payload string specific to Android platform [Refer this FCM officiallink].ibmenhuaweibody(string) - Set payload string specific to Android platform [Refer this FCM officiallink].ibmenapnsbody(string) - Set payload string specific to iOS platform [Refer this APNs official doclink].ibmensafaribody(string) - Set payload string specific to safari platform [Refer this Safari official doclink].ibmenapnsheaders(string) - Set headers required for the APNs message [Refer this APNs officiallink(Table 1 Header fields for a POST request)]ibmenchromebody(string) - Message body for the Chrome notifications. Referthis official documentationfor more.ibmenfirefoxbody(string) - Message body for the Firefox notifications. Referthis official documentationfor more.ibmenchromeheaders(string) - Headers for the Chrome notifications. Referthis official documentationfor more.ibmenfirefoxheaders(string) - Headers for the Firefox notifications. Referthis official documentationfor more.ibmendefaultshort* (string) - Default short text for the message.ibmendefaultlong* (string) - Default long text for the message.specversion* (string) - Spec version of the Event Notifications. Default value is1.0.ibmenhtmlbody* (string) - The html body of notification for email.ibmenmailto* (Array of string) - Array of email ids to which the notification to be sent.ibmensmsto* (Array of string) - Array of SMS numbers to which the notification to be sent.Note: variable with * represents the mandatory attribute.Set EnvironmentFindevent_notifications_v1.env.hidein the repo and rename it toevent_notifications_v1.env. After that add the values for,EVENT_NOTIFICATIONS_URL- Add the Event Notifications service instance Url.EVENT_NOTIFICATIONS_APIKEY- Add the Event Notifications service instance apikey.EVENT_NOTIFICATIONS_GUID- Add the Event Notifications service instance GUID.OptionalEVENT_NOTIFICATIONS_AUTH_URL- Add the IAM url if you are using IBM test cloud.EVENT_NOTIFICATIONS_FCM_KEY- Add firebase server key for Android FCM destination.EVENT_NOTIFICATIONS_FCM_ID- Add firebase sender Id for Android FCM destination.QuestionsIf you are having difficulties using this SDK or have a question about the IBM Cloud services,
please ask a questionStack Overflow.IssuesIf you encounter an issue with the project, you are welcome to submit abug report.
Before that, please search for similar issues. It's possible that someone has already reported the problem.Open source @ IBMFind more open source projects on theIBM Github PageContributingSeeCONTRIBUTING.md.LicenseThis SDK is released under the Apache 2.0 license.
The license's full text can be found inLICENSE.