Sending Notifications

Sending a Notification

The Airship Python Library strives to match the standard Airship API v3 JSON format for specifying notifications. When creating a notification, you:

  1. Select the audience

  2. Define the notification payload

  3. Specify device types.

  4. Deliver the notification.

This example performs a broadcast with the same alert to all recipients to a specific device type which can be list of types:

import urbanairship as ua
airship = ua.Airship(app_key, master_secret)

push = airship.create_push()
push.audience = ua.all_
push.notification = ua.notification(alert='Hello, world!')
push.device_types = ua.device_types('android', 'ios')
push.send()

Audience Selectors

An audience should specify one or more devices. An audience can be a device, such as a channel, a tag, alias, segment, location, or a combination. Audience selectors are combined with and_, or_, and not_.

urbanairship.push.all_

Select all, to do a broadcast.

push.audience = ua.all_
urbanairship.push.audience.ios_channel(uuid: str) Dict[str, str]

Select a single iOS Channel

urbanairship.push.audience.android_channel(uuid: str) Dict[str, str]

Select a single Android Channel

urbanairship.push.audience.amazon_channel(uuid: str) Dict[str, str]

Select a single Amazon Channel

urbanairship.push.audience.device_token(token: str) Dict[str, str]

Select a single iOS device token

urbanairship.push.audience.apid(uuid: str) Dict[str, str]

Select a single Android APID

urbanairship.push.audience.channel(uuid: str) Dict[str, str]

Select a single channel. This selector may be used for any channel_id, regardless of device type

urbanairship.push.audience.open_channel(uuid: str) Dict[str, str]

Select a single Open Channel

urbanairship.push.audience.sms_sender(sender: str) Dict[str, str]

Select an SMS Sender

urbanairship.push.audience.sms_id(msisdn: str, sender: str) Dict[str, Dict]

Select an SMS MSISDN

urbanairship.push.audience.wns(uuid: str) Dict[str, str]

Select a single Windows 8 APID

urbanairship.push.audience.tag(tag: str) Dict[str, str]

Select a single device tag.

urbanairship.push.audience.tag_group(tag_group: str, tag: str) Dict[str, str]

Select a tag group and a tag.

urbanairship.push.audience.alias(alias: str) Dict[str, str]

Select a single alias.

urbanairship.push.audience.segment(segment: str) Dict[str, str]

Select a single segment.

urbanairship.push.audience.named_user(name: str) Dict[str, str]

Select a Named User ID

urbanairship.push.audience.subscription_list(list_id: str) Dict[str, str]

Select a subscription list

urbanairship.push.audience.static_list(list_id: str) Dict[str, str]

Select a static list

urbanairship.push.audience.date_attribute(attribute: str, operator: str, precision: Optional[str] = None, value: Optional[Union[str, int]] = None) Dict[str, Any]

Select an audience to send to based on an attribute object with a DATE schema type, including predefined and device attributes. Please refer to https://docs.airship.com/api/ua/?http#schemas-dateattribute for more information about using this selector, including information about required data formatting for values. Custom attributes must be defined in the Airship UI prior to use.

urbanairship.push.audience.text_attribute(attribute: str, operator: str, value: str) Dict[str, Any]

Select an audience to send to based on an attribute object with a TEXT schema type, including predefined and device attributes.

Please refer to https://docs.airship.com/api/ua/?http#schemas-textattribute for more information about using this selector, including information about required data formatting for values.

Custom attributes must be defined in the Airship UI prior to use.

urbanairship.push.audience.number_attribute(attribute: str, operator: str, value: int) Dict[str, Any]

Select an audience to send to based on an attribute object with a INTEGER schema type, including predefined and device attributes.

Please refer to https://docs.airship.com/api/ua/?http#schemas-numberattribute for more information about using this selector, including information about required data formatting for values.

Custom attributes must be defined in the Airship UI prior to use.

urbanairship.push.audience.or_(*children: Any) Dict[str, Any]

Select devices that match at least one of the given selectors.

>>> or_(tag('sports'), tag('business'))
{'or': [{'tag': 'sports'}, {'tag': 'business'}]}
urbanairship.push.audience.and_(*children: Any) Dict[str, Any]

Select devices that match all of the given selectors.

>>> and_(tag('sports'), tag('business'))
{'and': [{'tag': 'sports'}, {'tag': 'business'}]}
urbanairship.push.audience.not_(child: Any) Dict[str, Any]

Select devices that does not match the given selectors.

>>> not_(and_(tag('sports'), tag('business')))
{'not': {'and': [{'tag': 'sports'}, {'tag': 'business'}]}}

Notification Payload

The notification payload determines what message and data is sent to a device. At its simplest, it consists of a single string-valued attribute, alert, which sends a push notification consisting of a single piece of text:

push.notification = ua.notification(alert='Hello, world!')

You can override the payload with platform-specific values as well.

urbanairship.push.payload.notification(alert: Optional[str] = None, ios: Optional[Dict] = None, android: Optional[Dict] = None, amazon: Optional[Dict] = None, web: Optional[Dict] = None, wns: Optional[Dict] = None, actions: Optional[Dict] = None, interactive: Optional[Dict] = None, in_app: Optional[Dict] = None, open_platform: Optional[Dict] = None, sms: Optional[Dict] = None, email: Optional[Dict] = None) Dict[str, Any]

Create a notification payload.

Parameters
  • alert – A simple text alert, applicable for all platforms.

  • ios – An iOS platform override, as generated by ios().

  • android – An Android platform override, as generated by android().

  • amazon – An Amazon platform override, as generated by amazon().

  • web – A web platform override, as generated by web().

  • wns – A WNS platform override, as generated by wns().

  • sms – An Sms platform override as generated by sms().

  • actions – Used to perform a defined task.

  • interactive – A dictionary with two attributes – “type” and “button_actions”, as generated by interactive().

  • open_platform – A dictionary with open platform name keys, and open platform overrides, as generated by open_platform().

urbanairship.push.payload.ios(alert: Optional[Union[str, Dict]] = None, badge: Optional[Union[str, int]] = None, sound: Optional[Union[str, Dict]] = None, content_available: bool = False, extra: Optional[Dict[str, Any]] = None, expiry: Optional[Union[str, int]] = None, interactive: Optional[Dict[str, Any]] = None, category: Optional[str] = None, title: Optional[str] = None, mutable_content: Optional[bool] = None, subtitle: Optional[str] = None, media_attachment: Optional[Dict] = None, priority: Optional[int] = None, collapse_id: Optional[str] = None, thread_id: Optional[str] = None, interruption_level: Optional[str] = None, relevance_score: Optional[float] = None, target_content_id: Optional[str] = None) Dict[str, Any]

iOS specific platform override payload.

Parameters
  • alert – iOS format alert, as either a string or dictionary. If a dictionary, the accepted keys must match those in Apple’s Payload Key Reference. Some options are only available with certain iOS versions on the device being sent to.

  • badge – An integer badge value or an autobadge string.

  • sound – If a string, the name of a sound file in the app bundle. If a dict, the ‘name’ key specifies the name of the sound file. Some options require iOS 12 or above on the device.

  • content_available – If true, the payload is delivered to your app in the background. This flag is automatically set to true if there is an In-App Message in the payload.

  • extra – A set of key/value pairs to include in the push payload sent to the device.

  • expiry – An integer or time set in UTC as a string

  • interactive – A dictionary with two attributes – “type” and “button_actions”, as generated by interactive().

  • category – A keyword used to categorize the notification. Must be a string

  • title – Sets the title of the notification for Apple Watch. Must be a string

  • mutable_content – Optional, a boolean. Defaults to false. When set to true, content may be modified by an extension. This flag will be automatically set to true if there is a media_attachment in the payload. iOS 10 or above.

  • subtitle – Optional, a string that will display below the title of the notification. This is provided as a convenience for setting the subtitle in the alert JSON object. If a subtitle is also defined in the alert JSON object, this value is ignored. iOS 10 or above.

  • media_attachment – Optional, a dictionary object Media Attachment. Specifies a media attachment to be handled by the UA Media Attachment Extension.

  • collapse_id – Optional, a string. When there is a newer message that renders an older, related message irrelevant to the client app, the new message replaces the older message with the same collapse_id. Similar to the GCM collapse_key. The value of this key must not exceed 64 bytes. iOS 10 or above.

  • thread_id – Optional, a string. A unique identifier used to group notifications into separate threads in the Notification Center and on the lock screen. Grouped notifications are available beginning with iOS 12.

  • interruption_level – Optional, a string. Indicates the importance and delivery timing of a notification. Must be one of: passive, active, time-sensitive, critical. Note: Use of the ‘critical’ levels requires an entitlement grant from Apple. Once this grant has been enabled, contact Airship Support to enable support with our APIs.

  • relevance_score – Optional, a number from 0.0 to 1.0. Used to sort notifications for an app. The notification with highest score is featured in the notification summary.

Target_content_id

Optional, a string. The identifier of the window to bring forward when the notification is opened. Used for multi-window content, such as App Clips.

>>> ios(alert='Hello!', sound='cat.caf',
...     extra={'articleid': '12345'}) 
{'sound': 'cat.caf', 'extra': {'articleid': '12345'}, 'alert': 'Hello!'}
urbanairship.push.payload.android(alert: Optional[str] = None, collapse_key: Optional[str] = None, time_to_live: Optional[int] = None, delay_while_idle: Optional[bool] = False, extra: Optional[Dict] = None, interactive: Optional[Dict] = None, local_only: Optional[bool] = None, wearable: Optional[Dict] = None, delivery_priority: Optional[str] = None, style: Optional[Dict] = None, title: Optional[str] = None, summary: Optional[str] = None, sound: Optional[str] = None, priority: Optional[int] = None, category: Optional[str] = None, visibility: Optional[int] = None, public_notification: Optional[Dict] = None, notification_tag: Optional[str] = None, notification_channel: Optional[str] = None, icon: Optional[str] = None, icon_color: Optional[str] = None) Dict[str, Any]

Android specific platform override payload.

All keyword arguments are optional.

Parameters
  • alert – String alert text.

  • collapse_key – String

  • time_to_live – Integer

  • delay_while_idle – Boolean

  • extra – A set of key/value pairs to include in the push payload sent to the device. All values must be strings.

  • interactive – A dictionary with two attributes – “type” and “button_actions”, as generated by interactive().

  • local_only – Optional value for not showing the notification on wearable devices. Defaults to False.

  • wearable – Optional object to define a wearable notification with the following optional fields: background_image, extra_pages, and interactive.

  • delivery_priority – Optional string of either ‘high’ or ‘normal’. Sets the GCM priority.

  • style – Optional object. Defines an advanced style.

  • title – Optional string. Represents the title of the notification.

  • summary – Optional string. Represents a summary of the notification.

  • sound – Optional string. Represents a sound file name included in the app resources.

  • priority – Optional integer between -2 and 2. An Android L feature that determines location sort order.

  • category – Optional string. An Android category.

  • visibility – Optional integer between -1 and 1.

  • public_notification – Optional object. A notification to show on the lock screen instead instead of the redacted one.

  • notification_tag – Optional string. A string identifier used to replace an existing notification in the notification drawer.

  • notification_channel – Optional string. An identifier of a notification channel predefined by the application.

  • icon – Optional string. The name of a drawable in the application’s resource directory.

  • icon_color – Optional. A string in the format of #rrggbb that defines the notification accent color.

See GCM Advanced Topics for details on collapse_key, time_to_live, and delay_while_idle.

>>> android(alert='Hello!', extra={'articleid': '12345'}) 
{'extra': {'articleid': '12345'}, 'alert': 'Hello!'}
urbanairship.push.payload.amazon(alert: Optional[str] = None, consolidation_key: Optional[str] = None, expires_after: Optional[Union[str, int]] = None, extra: Optional[Dict] = None, title: Optional[str] = None, summary: Optional[str] = None, interactive: Optional[Dict] = None, style: Optional[str] = None, sound: Optional[str] = None, icon: Optional[str] = None, icon_color: Optional[str] = None, notification_channel: Optional[str] = None, notification_tag: Optional[str] = None) Dict[str, Any]

Amazon specific platform override payload.

All keyword arguments are optional.

Parameters
  • alert – String alert text.

  • consolidation_key – String

  • expires_after – Integer or UTC time (string)

  • extra – A set of key/value pairs to include in the push payload sent to the device. All values must be strings.

  • title – String

  • summary – String

  • interactive – A dictionary with two attributes – “type” and “button_actions”, as generated by interactive().

  • notification_tag – Optional string. A string identifier used to replace an existing notification in the notification drawer.

  • notification_channel – Optional string. An identifier of a notification channel predefined by the application.

  • icon – Optional string. The name of a drawable in the application’s resource directory.

  • icon_color – Optional. A string in the format of #rrggbb that defines the notification icon accent color.

>>> amazon(alert='Hello!', title='My Title',
...     extra={'articleid': '12345'}) 
{'title': 'My Title', 'extra': {'articleid': '12345'}, 'alert': 'Hello!'}
urbanairship.push.payload.web(alert: Optional[str] = None, extra: Optional[Dict] = None, icon: Optional[Dict] = None, title: Optional[str] = None, interactive: Optional[Dict] = None, time_to_live: Optional[Union[str, int]] = None, require_interaction: Optional[bool] = None) Dict[str, Any]

Web specific platform override payload.

All keyword arguments are optional

Parameters
  • alert – An optional string alert text.

  • extra – An optional set of key/value pairs to include in the push payload sent to the device.

  • icon – An optional JSON dictionary of string key and value pairs. Key must be ‘url’ and value, an HTTPS URL to the icon resource.

  • title – Optional string. Represents the title of the notification.

  • interactive – An optional dictionary with two attributes – type and button_actions, as generated by interactive()

  • time_to_live – An optional integer or time set in UTC as a string

  • require_interaction – An optional boolean value that requires user interaction on the notification before it is dismissed.

>>> web(extra={'articleid': '12345'},
...    icon={'url': 'https://example.com/icon.png'},
...    title='This is a title!') 
{'title': 'This is a title!', 'extra': {'articleid': '12345'},
 'icon': {'url': 'https://example.com/icon.png'}, 'alert': 'Hello!'}
urbanairship.push.payload.sms(alert: Optional[str] = None, expiry: Optional[Union[str, int]] = None, template_alert: Optional[str] = None, shorten_links: Optional[bool] = None) Dict[str, Any]

Sms platform specific override payload See: https://docs.airship.com/api/ua/#schemas-smsoverrideobject One of alert or template_alert must be used.

Parameters
  • alert – An optional string. Overrides the alert provided at the top level of the notification for Sms channels. The maximum length of an Sms alert is 1600 characters.

  • template_alert – for use with CreateAndSendPush. Substitutions must be added to the Sms objects passed to CreateAndSendPush that match the bracketed fields in this alert string.

  • expiry – Optional. Delivery expiration, as either absolute UTC timestamp (string), or number of seconds from now (integer).

  • shorten_links – Optional. If true, Airship will shorten http/https links (space delimited) in the message text fields, producing unique, 25 character URLs for each member of your audience. If using this feature, please see the documentation linked above.

>>> sms(alert='sms override alert!', expiry='2018-04-01T12:00:00') 
{'alert': 'sms override alert!', 'expiry': '2018-04-01T12:00:00'}
urbanairship.push.payload.mms(fallback_text: str, content_type: str, url: str, shorten_links: Optional[bool] = None, content_length: Optional[int] = None, text: Optional[str] = None, subject: Optional[str] = None) Dict[str, Any]

Provides the content for a push to MMS channels. If sms is in the device_type array, your request may include this object. It cannot be combined with an SMS Platform Override as a single push can only include either an SMS or MMS payload. Please see the documentation here: https://docs.airship.com/api/ua/#schemas-mmsoverrideobject

Parameters
  • fallback_text – Required. If a member of your audience cannot receive MMS messages, they will receive your fallback text with a link to the original content.

  • content_type – Required. The MIME type of the image specified in the URL. The MIME type must match the extension in the url.

  • url – Required. The http or https URL of the media attachment for the slide. The URL must end in one of .gif, .jpeg, .jpg, .png, or .vcf (case-insensitive). While the content_length field is optional, your image must still be under 2MB for JPEGs and PNGs, 1 MB for GIFs, or 2048000 bytes for text/vcard.

  • shorten_links – Optional. If true, Airship will shorten http/https links (space delimited) in the message text fields, producing unique, 25 character URLs for each member of your audience. If using this feature, please see the documentation linked above.

  • content_length – Optional. The length of the attachment in bytes. If using this feature, please see the documentation linked above.

  • text – Optional. Text that you want to display along with the media attachment. The order of media and text in the message is not guaranteed.

  • subject – Optional. The subject for the MMS message, normally displayed in bold. The subject might not appear for recipients if the Sender is a Toll-Free number.

urbanairship.push.payload.email(message_type: str, plaintext_body: str, reply_to: str, sender_address: str, sender_name: str, subject: str, attachments: Optional[List[str]] = None, html_body: Optional[str] = None, variable_defaults: Optional[Dict[str, str]] = None, bcc: Optional[List[str]] = None, bypass_opt_in_level: Optional[bool] = None, click_tracking: Optional[bool] = None, open_tracking: Optional[bool] = None)

Required platform override when email in ua.device_types. Specifies content of the email being sent. All other notification fields are not used in the email if included.

See https://docs.airship.com/api/ua/#schemas-emailoverrideobject for additional caveats.

Parameters
  • message_type – Required. One of transactional or commercial.

  • plaintext_body – Required. The plain text body of the email. May include variable substitution fields for use with create and send inline templates.

  • reply_to – Required. The reply-to address.

  • sender_address – Required. The email address of the sender. The domain of the email must be enabled in the email provider at the delivery tier.

  • sender_name – Required. The common name of the email sender.

  • subject – Required. The subject line of the email. May include variable substitution fields for use with create and send inline templates.

  • html_body – Optional. The HTML content of the email.

  • variable_details – Required for CreateAndSendPush with inline templates. a list of dicts of default values for inline template variables.

  • attachments – Optional. A list of attachment_id values from the API.

  • bcc – Optional. A list of email addresses that you want to blind copy on this email. Using addresses that Airship has not enabled for BCC will return a 400.

  • bypass_opt_in_level – Optional. You can set this toggle when message_type is set to transactional to send a business critical email. If true, the message will be sent to your entire audience, ignoring transactional_opted_out status.

  • click_tracking – Optional. True by default. Set to False to prevent click tracking for GDPR compliance.

  • open_tracking – Optional. True by default. Set to False to prevent “open” tracking for GDPR compliance.

urbanairship.push.payload.open_platform(alert: Optional[str] = None, title: Optional[str] = None, extra: Optional[Dict[str, Any]] = None, summary: Optional[str] = None, media_attachment: Optional[str] = None, interactive: Optional[Dict[str, Any]] = None, template_alert: Optional[str] = None) Dict[str, Any]

Open platform specific override payload.

All keyword arguments are optional.

Parameters
  • alert – String alert text.

  • title – String, represents the title of the notification.

  • summary – A string value for providing a content summary.

  • media_attachment – A URI for an image or video somewhere on the internet.

  • extra – A set of key/value pairs to include in the push payload sent to the device.

  • interactive – An interactive payload override, as generated by interactive(). Included button actions must be of type add_tag, remove tag, app_defined, or open with subtype url.

  • template_alert – For use with CreateAndSendPush. A string with inline template substitution fields. The name of these must match subsititutions on the OpenChannel objects used with CreateAndSendPush.

>>> sms_overrides = open_platform(
...    alert='Hello!',
...    title='See my new homepage!',
...    summary='A longer summary of some content',
...    media_attachment='https://example.com/cat_standing_up.jpeg',
...    extra={'some_info': 'for sms only'},
...    interactive=interactive(
...            type='ua_yes_no_foreground',
...            button_actions={
...                'yes': actions(open_={
...                    'type':'url',
...                    'content':'https://www.urbanairship.com'
...                    }),
...                'no': actions(app_defined={'foo': 'bar'})
...            }
...        ) 
{'alert': 'Hello!', 'title': 'See my new homepage!', 'summary':
'A longer summary of some content', 'media_attachment':
'https://example.com/cat_standing_up.jpeg', 'extra': {'some_info':
'for sms only'}, 'interactive': {'type': 'ua_yes_no_foreground',
'button_actions': { 'yes': {'open': {'type': 'url', 'content':
'http://www.urbanairship.com'}}, 'no': {'app_defined': {'foo': 'bar'}}}}}
>>> notification(open_platform={'sms': sms_overrides}) 
urbanairship.push.payload.wns_payload(alert: Optional[str] = None, toast: Optional[str] = None, tile: Optional[str] = None, badge: Optional[str] = None) Dict[str, Any]

WNS specific platform override payload.

Must include exactly one of alert, toast, tile, or badge.

urbanairship.push.payload.message(title: str, body: str, content_type: Optional[str] = None, content_encoding: Optional[str] = None, extra: Optional[Dict[str, Any]] = None, expiry: Optional[Union[str, int]] = None, icons: Optional[Dict] = None, options: Optional[Dict[Any, Any]] = None, campaigns: Optional[Dict[str, Any]] = None) Dict[str, Any]

Rich push message payload creation.

Parameters
  • title – Required, string

  • body – Required, string

  • content_type – Optional, MIME type of the body

  • content_encoding – Optional, encoding of the data in body, e.g. utf-8.

  • extra – Optional, dictionary of string values.

  • expiry – time when message will delete from Inbox (UTC time or in seconds)

  • icons – Optional JSON dictionary of string key and value pairs. Values must be URIs or URLs to the icon resources

  • options – Optional JSON dictionary of key and value pairs specifying non-payload options

  • campaigns – Optional dictionary containing list of 1 to 10 ‘categories’

urbanairship.push.payload.in_app(alert: str, display_type: str, expiry: Optional[str] = None, display: Optional[Dict[str, Any]] = None, actions: Optional[Dict[str, Any]] = None, interactive: Optional[Dict[str, Any]] = None, extra: Optional[Dict[str, Any]] = None) Dict[str, Any]

In-App push message payload creation.

Parameters
  • alert – Required, string

  • display_type – Required, String. List of valid display_type attributes.

  • expiry – Optional, String specifying an expiry value.

  • display – Optional, A dictionary specifying the display appearance of the in-app message.

  • actions – Optional, Used to perform a defined task.

  • interactive – Optional, A dictionary with two attributes – “type” and “button_actions”, as generated by interactive().

  • extra – Optional, Object.

urbanairship.push.payload.options(expiry: Optional[Union[str, int]] = None) Dict[str, Any]

Options payload creation.

Parameters

expiry – time at which push will no longer be sent. Int or UTC time

urbanairship.push.payload.campaigns(categories: Optional[Union[Dict, List]] = None) Dict[str, Any]

Campaigns payload creation.

>>> campaigns(categories=['kittens', 'tacos', 'horse_racing'])
{'categories': ['kittens', 'tacos', 'horse_racing']}
urbanairship.push.payload.actions(add_tag: Optional[Union[str, List[str]]] = None, remove_tag: Optional[Union[str, List[str]]] = None, open_: Optional[Dict[str, Any]] = None, share: Optional[str] = None, app_defined: Optional[Dict[str, Any]] = None) Dict[str, Any]

Actions payload creation.

Parameters
  • add_tag – Adds a tag to the device. Expects a string or a list of strings.

  • remove_tag – Removes a tag from the device. Expects a string or a list of strings.

  • open – Opens type url, deep_link or landing_page. Expects a dictionary with “type” and “content”. See API docs for more information.

  • share – Sends a share notification. Expects a string.

  • app_defined – Sends application defined actions. Expects a dictionary.

>>> actions(add_tag='new_tag', remove_tag='old_tag',
...     open_={'type': 'url',
...         'content': 'http://www.urbanairship.com'}) 
{'open': {'type': 'url', 'content': 'http://www.urbanairship.com},
 'add_tag': 'new_tag', 'remove_tag': 'old_tag'}
urbanairship.push.payload.interactive(type: Optional[str] = None, button_actions: Optional[Dict[str, Any]] = None) Dict[str, Any]

Interactive payload creation.

Parameters
  • type – The name of one of the predefined interactive notifications or a custom defined interactive notification. Expects a string.

  • button_actions – A button_actions object that maps button IDs to valid action objects. Expects a dictionary.

urbanairship.push.payload.wearable(background_image: Optional[str] = None, extra_pages: Optional[List[str]] = None, interactive: Optional[Dict[str, Any]] = None) Dict[str, Any]

Android wearable payload builder.

Parameters
  • background_image – Optional string. A URL that specifies the background image to display on a wearable device.

  • extra_pages – Optional array of objects.

  • interactive – Optional object. Override the interactive notification payload for the wearable device.

urbanairship.push.payload.public_notification(title: Optional[str] = None, alert: Optional[str] = None, summary: Optional[str] = None) Dict[str, Any]

Android L public notification payload builder.

Parameters
  • title – Optional string. The notification title.

  • alert – Optional string. The notification alert.

  • summary – Optional string. The notification summary.

urbanairship.push.payload.style(style_type: Optional[str], content: Optional[Union[str, List[str]]], title: Optional[str] = None, summary: Optional[str] = None) Dict[str, Any]

Android/Amazon style builder.

Parameters
  • style_type – String. Must be one of “big_text”, “big_picture”, or “inbox”.

  • content – String or array of strings. Content of the style object. If style_type is set to “inbox”, this will be an array of strings. Otherwise, it will be a single string.

  • title – Optional string. Override the notification.

  • summary – Optional string. Override the summary of the notification.

urbanairship.push.payload.media_attachment(url: str, content: Optional[Dict[str, Any]] = None, options: Optional[Dict[str, Any]] = None) Dict[str, Any]

iOS media_attachment builder.

Parameters
  • url – String. Specifies the URL to be downloaded by the UA Media Attachment extension.

  • content – Optional dictionary. Describes portions of the notification that should be modified if the media attachment succeeds. See content().

  • options – Optional dictionary. Describes how to display the resource given by the URL. See options().

urbanairship.push.payload.content(title: Optional[str] = None, subtitle: Optional[str] = None, body: Optional[str] = None) Dict[str, Any]

iOS content builder. Each argument describes the portions of the notification that should be modified if the media_attachment succeeds.

Parameters
  • title – String.

  • subtitle – String.

  • body – String.

urbanairship.push.payload.crop(x: Optional[float] = None, y: Optional[float] = None, width: Optional[float] = None, height: Optional[float] = None) Dict[str, Any]

iOS crop builder.

Parameters
  • x – Optional float. The X offset where the crop begins.

  • y – Optional float. The Y offset where the crop begins.

  • width – Optional float. The width of the final crop.

  • height – Optional float. The height of the final crop.

urbanairship.push.payload.localization(language: Optional[str] = None, country: Optional[str] = None, notification: Optional[Dict[str, Any]] = None, message: Optional[Dict[str, Any]] = None, in_app: Optional[Dict[str, Any]] = None) Dict[str, Any]

Localized content for a push notification, message center message, or in app message. Localization must include at least one of language or country. Localization content must include at least one of notification, message, or in_app.

Parameters
  • language – Optional. The ISO 639-1 two-letter language code for this localization.

  • country – Optional. The ISO 3166-2 two-letter country code for this localization.

  • notification – Optional. An urbanairship.notification containing localized push notification content.

  • message – Optional. An urbanairship.message containing localized message center content.

  • in_app – Optional. An urbanarship.in_app containing localized in_app content.

Device Types

In addition to specifying the audience, you must specify the device types you wish to target with one or more strings:

push.device_types = ua.device_types('ios')
push.device_types = ua.device_types('android', 'ios', 'web')
urbanairship.push.payload.device_types(*types: Any) Union[str, List[str]]

Create a device type specifier.

>>> device_types('ios', 'wns')
['ios', 'wns']
>>> device_types('ios', 'symbian')
Traceback (most recent call last):
    ...
ValueError: Invalid device type 'symbian'

Immediate Delivery

Once you have set the audience, notification, and device_types attributes, the notification is ready for delivery. Use Push.send() to send immediately.

push.send()

If the request is unsuccessful, an AirshipFailure exception will be raised.

class urbanairship.push.core.Push(airship: urbanairship.core.Airship)

A push notification. Set audience, message, etc, and send.

validate() urbanairship.push.core.PushResponse

Test push payload against the validate endpoint. No sends will result from this method being called. This method is otherwise identical to the send method.

send() urbanairship.push.core.PushResponse

Send the notification.

Returns

PushResponse object with push_ids and other response data.

Raises
  • AirshipFailure – Request failed.

  • Unauthorized – Authentication failed.

  • ValueError – Required keys missing or incorrect values included.

Scheduled Delivery

Schedule notifications for later delivery.

Examples can be found in the documentation here.

class urbanairship.push.core.ScheduledPush(airship: urbanairship.core.Airship)

A scheduled push notification. Set schedule, push, and send.

send() urbanairship.push.core.PushResponse

Schedule the notification

Returns

PushResponse object with schedule_url and other response data.

Raises
validate() urbanairship.push.core.PushResponse

Validates a scheduled push for sending

pause() requests.models.Response

Pause a recurring schedule

resume() requests.models.Response

Resume a paused recurring schedule

cancel() requests.models.Response

Cancel a previously scheduled notification.

Scheduled Time Builders

urbanairship.push.schedule.scheduled_time(timestamp: datetime.datetime) Dict[str, Any]

Specify a time for the delivery of this push.

Parameters

timestamp – A datetime.datetime object.

urbanairship.push.schedule.local_scheduled_time(timestamp: datetime.datetime) Dict[str, Any]

Specify a time for the delivery of this push in device local time.

Parameters

timestamp – A datetime.datetime object.

urbanairship.push.schedule.best_time(timestamp: datetime.datetime) Dict[str, Any]

Specify a date to send the push at the best time per-device. Only YYYY_MM_DD are needed. Hour/minute/second information is discarded.

Parameters

timestamp – A datetime.datetime object.

urbanairship.push.schedule.recurring_schedule(count: int, type: str, end_time: Optional[datetime.datetime] = None, days_of_week: Optional[List[str]] = None, exclusions: Optional[List[Dict[str, Any]]] = None, paused: Optional[bool] = False) Dict[str, Any]

Sets the cadence, end time, and excluded times for a recurring scheduled message.

Parameters
  • count – Required. The frequency of messaging corresponding to the type. For example, a count of 2 results in a message every 2 hours, days, weeks, months, etc based on the type.

  • type – Required. The unit of measurement for the cadence. Possible values: hourly, daily, monthly, yearly.

  • days_of_week – Required when type is weekly. The days of the week on which Airship can send your message.

  • end_time – Optional. A datetime.datetime object representing when the scheduled send will end and stop sending messages.

  • exclusions – Optional. A list of urbanaiship.schedule_exclusion defining times in which Airship will not send your message.

  • paused – Optional. A boolean value respesnting the paused state of the scheduled message.

urbanairship.push.schedule.schedule_exclusion(start_hour: Optional[int] = None, end_hour: Optional[int] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, days_of_week: Optional[List[str]] = None) Dict[str, Any]

Date-time ranges when messages are not sent. at least one of start_hour and end_hour, start_date and end_date, or days_of_week must be included. All dates and times are inclusive.

Parameters
  • start_hour – Optional. An integer 0-23 representing the UTC hour to start exclusion.

  • end_hour – Optional. An integer 0-23 representing the UTC hour to stop exclusion. Must be included if start_hour is used.

  • start_date – Optional. A datetime.datetime object representing the UTC date to start exclusion. Hour/minute/seconds will be excluded.

  • start_date – Optional. A datetime.datetime object representing the UTC date to stop exclusion. Hour/minute/seconds will be excluded. Must be included if start_date is used.

  • days_of_week – Optional. A list of the days of the week to exclude on. Possible values: monday, tuesday, wednesday, thursday, friday, saturday, sunday

List Scheduled Notifications

class urbanairship.push.schedule.ScheduledList(airship: urbanairship.core.Airship, limit: Optional[int] = None)

Iterator for listing all scheduled messages.

Parameters

limit – Number of entries to fetch in a paginated request.

Returns

Each next returns a ScheduledPush object.

Personalization

Send a notification with personalized content.

Examples can be found in the schedules documentation here.

class urbanairship.push.core.TemplatePush(airship)

A personalized push notification. Set details and send.

send() urbanairship.push.core.PushResponse

Send the personalized notification.

Returns

PushResponse object with push_ids and other response data.

Raises

Template

class urbanairship.push.template.Template(airship: urbanairship.core.Airship, name: Optional[str] = None, description: Optional[str] = None, variables: Optional[List[Dict[str, Any]]] = None, push: Optional[Type[urbanairship.push.core.Push]] = None)

Information object for a template.

Parameters
  • template_id – UUID; the ID of this template, set automatically.

  • created_at – UTC datetime when the template was created.

  • modified_at – UTC datetime when the template was last modified.

  • last_used – UTC datetime when the template was last used for a push notification. Will be set to ‘UNKNOWN’ if never used.

  • name – Required, name of the template, set during creation/modification.

  • description – Optional, description of the template, set during creation/modification.

  • variables – Required, an array of Template Variable Objects.

  • push – Optional, a push specification object, as defined by the Push Object specification, but does not include audience or device_types since those are set when push messages are sent. Message Center message is also not supported in Templates at this time.

create() requests.models.Response

Create a notification template with the API.

Raises
update(template_id: Optional[str] = None) requests.models.Response

Update a template with the API.

Raises
delete(template_id: Optional[str] = None) requests.models.Response

Delete a previously created template.

Raises

Template Lookup

class urbanairship.push.template.Template(airship: urbanairship.core.Airship, name: Optional[str] = None, description: Optional[str] = None, variables: Optional[List[Dict[str, Any]]] = None, push: Optional[Type[urbanairship.push.core.Push]] = None)

Information object for a template.

Parameters
  • template_id – UUID; the ID of this template, set automatically.

  • created_at – UTC datetime when the template was created.

  • modified_at – UTC datetime when the template was last modified.

  • last_used – UTC datetime when the template was last used for a push notification. Will be set to ‘UNKNOWN’ if never used.

  • name – Required, name of the template, set during creation/modification.

  • description – Optional, description of the template, set during creation/modification.

  • variables

    Required, an array of Template Variable Objects.

  • push

    Optional, a push specification object, as defined by the Push Object specification, but does not include audience or device_types since those are set when push messages are sent. Message Center message is also not supported in Templates at this time.

lookup(template_id)

Fetch metadata from a template ID

Template Listing

class urbanairship.push.template.TemplateList(airship, limit=None)

Iterator for listing all templates for this application.

Parameters

limit – Number of entries to fetch in each page request.

Returns

Each next returns a Template object.

Merge Data

urbanairship.push.template.merge_data(template_id: str, substitutions: Dict[str, Any]) Dict[str, Any]

Template push merge_data creation.

Parameters
  • template_id – Required, UUID.

  • substitutions – Required, dictionary of template variables and their substitutions, e.g. {“FIRST_NAME”: “Bob”, “LAST_NAME”: “Smith”}

Create and Send

Simultaneously send a notification to an audience of SMS, email, or open channel addresses and register channels for new addresses in your audience.

Examples can be found in the create and send documentation here.

class urbanairship.push.core.CreateAndSendPush(airship: urbanairship.core.Airship, channels: List)

Creates and sends to email, sms or open channels. Channel ids are created but not returned by this request. Use lookup/listing endpoints to find channel_id values. Opt-in date attributes are required on Sms and Email objects passed in.

Parameters
  • airship – Required. An urbanairship.Airship object instantiated with master authentication.

  • channels – Required. A list of Sms, Email or OpenChannel objects. channels may only be of one type and must match the single value for CreateAndSend.device_types.

send() urbanairship.push.core.PushResponse

Send the notification.

Returns

PushResponse object with push_ids and other response data.

Raises
  • AirshipFailure – Request failed.

  • Unauthorized – Authentication failed.

  • ValueError – Required keys missing or incorrect values included.

Automation

With the automation pipelines endpoint you can manage automations for an Airship project. Pipelines define the behavior to be triggered on user-defined events. For more information, see the documentation on Automation.

class urbanairship.automation.core.Automation(airship: urbanairship.core.Airship)

An object for getting and creating automations.

Parameters

airship – An urbanairship.Airship instance, instantiated with the key corresponding to the airship project you wish to use.

create(pipelines: Union[urbanairship.automation.pipeline.Pipeline, List[urbanairship.automation.pipeline.Pipeline]]) requests.models.Response

Create an automation with one or more Pipeline payloads

Parameters

pipelines – A single Pipeline payload or list of Pipeline payloads

validate(pipelines: Union[urbanairship.automation.pipeline.Pipeline, List[urbanairship.automation.pipeline.Pipeline]]) requests.models.Response

Validate a Pipeline payloads

Parameters

pipelines – A single Pipeline payload or list of Pipeline payloads

update(pipeline_id: str, pipeline: urbanairship.automation.pipeline.Pipeline) requests.models.Response

Update an existing Automation Pipeline

Parameters
  • pipeline_id – A Pipeline ID

  • pipeline – Full Pipeline payload; partial updates are not supported

delete(pipeline_id: str) requests.models.Response

Delete an existing Automation Pipeline

Parameters

pipeline_id – A Pipeline ID

lookup(pipeline_id: str) requests.models.Response

Lookup an Automation Pipeline

Parameters

pipeline_id – A Pipeline ID

list_automations(limit: Optional[int] = None, enabled: bool = False) requests.models.Response

List active Automations

Parameters
  • limit – Optional, maximum pipelines to return

  • enabled – Optional, boolean limiter for results to only enabled Pipelines

list_deleted_automations(start: Optional[str] = None) requests.models.Response

List deleted Automation Pipelines

Parameters

start – Optional starting timestamp for limiting results in ISO-8601 format

Pipeline

A pipeline object encapsulates the complete set of objects that define an Automation pipeline: Triggers, Outcomes, and metadata.

class urbanairship.automation.pipeline.Pipeline(enabled: Optional[bool] = None, name: Optional[str] = None, historical_trigger: Optional[Dict] = None, timing: Optional[Dict] = None, immediate_trigger: Optional[Union[Dict, List]] = None, cancellation_trigger: Optional[Union[Dict, List]] = None, constraint: Optional[Union[Dict, List]] = None, condition: Optional[Union[Dict, List]] = None, outcome: Optional[Union[Dict, List]] = None)

Pipeline object encapsulates the complete set of objects that define an Automation pipeline

Create Pipeline object for Automation payload

Parameters
  • enabled – boolean value determines active status of the pipeline

  • outcome – a push object to be sent as outcome of the pipeline

  • name – [optional] descriptive string for pipeline identification

  • immediate_trigger – [optional] single event identifier or list of event identifiers that trigger the outcome of the pipeline - trigger list can be combination of simple and compound identifiers

  • cancellation_trigger – [optional] single event identifier or list of event identifiers that trigger cancellation of the pipeline outcome - can be combination of simple and compound identifiers

  • historical_trigger – [optional] single or list of historical trigger objects that currently match only inactive triggers

  • constraint – [optional] single or list of constraint objects that limit the number of pushes sent to a device in a given time period

  • condition – [optional] one or a list of condition sets with an and/or operator for combining the conditions

  • timing – [optional] a timing object defining times allowable for outcome delivery

property payload: Dict

JSON serialized Pipeline object

append_outcome_object(push_object: Dict) None

Append outcome object to current Pipeline outcome

Parameters

push_object – A push object that will be an outcome for this Pipeline object

remove_outcome_object(push_object: Dict) None

Remove outcome push object from current outcome

Parameters

push_object – A push object to remove from the outcome of this Pipeline object

append_immediate_trigger_identifier(event_identifier: Dict) None

Append event identifier to immediate triggers for Pipeline

Parameters

event_identifier – Event identifier object

remove_immediate_trigger_identifier(event_identifier: Dict) None

Remove event identifier to immediate triggers for Pipeline

Parameters

event_identifier – Even identifier object

append_cancellation_trigger_identifier(event_identifier: Dict) None

Append event identifier to immediate triggers for Pipeline

Parameters

event_identifier – Event identifier object

remove_cancellation_trigger_identifier(event_identifier: Dict) None

Remove event identifier from immediate triggers for Pipeline

Parameters

event_identifier – Event identifier object

append_constraint_object(constraint_object: Dict) None

Append constraint object to constraint for Pipeline

Parameters

constraint_object – Constraint object to append to Pipeline constraint

append_condition_set(condition_set: Dict) None

Append condition set to Pipeline condition

Parameters

condition_set – One or list of condition sets

remove_condition_set(condition_set: Dict) None

Remove condition set from Pipeline condition

Parameters

condition_set – One or list of condition sets

A/B Tests

An A/B test is a set of distinct push notification variants sent to subsets of an audience. You can create up to 26 notification variants and send each variant to an audience subset

Examples can be found in the A/B Tests documentation here.

class urbanairship.experiments.core.ABTest(airship)
list_experiments() Dict

List experiments, sorted by created_at date/time from newest to oldest

Parameters

limit – Positive maximum number of elements to return per page. Default limit is 10. Max: 100 and Min: 1.

create(experiment: urbanairship.experiments.experiment.Experiment) Dict

Create an experiment

list_scheduled_experiment() Dict

List scheduled experiments in order, from closest to the current date-time to farthest

delete(experiment_id: str) Dict

Delete a scheduled experiment. You can only delete experiments before they start

Parameters

experiment_id – The unique identifier of the experiment, type string

validate(experiment: urbanairship.experiments.experiment.Experiment) Dict

Accepts the same range of payloads as /api/experiments, but only parses and validates the payload without creating the experiment. An experiment may validate and still fail to be delivered. For example, you may have a valid experiment with no devices in your audience.

Parameters

experiment – Body of the experiment you want to validate

lookup(experiment_id: str) Dict

Look up an experiment (A/B Test)

Parameters

experiment_id – The unique identifier of the experiment, type string

Experiment

class urbanairship.experiments.experiment.Experiment(audience: Dict[str, Any], device_types: List[str], variants: List[urbanairship.experiments.variant.Variant], name: Optional[str] = None, description: Optional[str] = None, weight: Optional[int] = None, campaigns: Optional[Dict[str, Any]] = None, control: Optional[float] = None)

An experiment object describes an A/B test, including the audience and variant portions.

Parameters
  • audience – [required] The audience for the experiment

  • device_types – A list containing one or more strings identifying targeted platforms. Accepted platforms are ios, android, amazon, wns, web, sms, email, and open::<open_platform_name>

  • variants – [required] The variants for the experiment. An experiment must have at least 1 variant and no more than 26.

  • name – [optional] A name for the experiment

  • description – [optional] A description of the experiment

  • campaigns – [optional] Campaigns object that will be applied to resulting pushes

  • control – [optional] The proportional subset of the audience that will not receive a push

property payload: Dict[str, Any]

JSON serialized experiment object

Variant

class urbanairship.experiments.variant.Variant(push, description=None, name=None, schedule=None, weight=None)

The variants for the experiment. An experiment must have at least 1 variant and no more than 26.

Parameters
  • push – [required] A push object without audience and device_types fields. These two fields are not allowed because they are already defined in the experiment object

  • description – [optional] A description of the variant.

  • name – [optional] A name for the variant unless either message or in_app is present. You can provide an alert and any platform overrides that apply to the device_type platforms you specify.

  • schedule – [optional] The time when the push notification should be sent

  • weight – [optional] The proportion of the audience that will receive this variant. Defaults to 1.