map-o file-code-o arrow-directionplatform-webreach-project-type-boarding-passreach-project-type-couponreach-project-type-event-ticketreach-project-type-genericreach-project-type-gift-cardreach-project-type-loyalty-cardreach-project-type-member-card pictures more_vert chain keyboard_arrow_down keyboard_arrow_right

Example API Requests

With the Urban Airship API, you can design and automate a complex messaging strategy, retrieve detailed analytics, and more. In order to help you begin testing in your own environment we have pulled together a collection of common use-cases, providing example requests in multiple languages.

This guide is neither an introduction to the Urban Airship API nor a full reference. Rather, this document serves as a middle ground — you should have a high-level understanding of our APIs before proceeding, but you are not expected to be an expert. We suggest that you read (or skim) our Integration Guide before attempting the implementations listed here.

Preliminaries

In the Urban Airship API Reference, example API requests/responses are provided in HTTP format with JSON data objects representing the features and attributes of the Urban Airship service. From time to time in our documentation or on our Support site, we may also provide convenient HTTP examples for use with the command-line tool cURL.

Understanding that cURL examples are primarily useful for testing, we endeavor to provide additional examples that you may be able to use in your production environment. To that end, we are including example requests here written in Python, Java, and Ruby, three of the multiple languages for which we currently provide support. See: Libraries.

This document evolves as we continue to add additional features and server library support. If you have any questions about this page or would like to suggest a new example, please send a note to our Support Team.

Java

Because Java code can be quite verbose, we have only included one full example: sending a push broadcast. Other Java examples have been reduced to the essential components.

UrbanAirshipClient client = UrbanAirshipClient.newBuilder()
   .setKey("<appKey>")
   .setSecret("<appSecret>")
   .build();

In particular, an UrbanAirshipClient object, referred to as client, is used repeatedly throughout the following examples. Unless explicitly stated otherwise, client is defined as:

Push

The Push API is used to send notifications to opted in devices. The process for sending a notification via the API can be abstracted to four steps:

  1. Select the audience.
  2. Define the notification payload.
  3. Specify device types.
  4. Deliver the notification.


This section gives complete examples for several common use cases.

Broadcast to All Devices

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": "all",
          "notification": { "alert" : "A broadcast message" },
          "device_types": "all"
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.all_
push.notification = ua.notification(alert='A broadcast message')
push.device_types = ua.all_
push.send()
import com.urbanairship.api.client.*;
import com.urbanairship.api.client.Response;
import com.urbanairship.api.push.PushRequest;
import com.urbanairship.api.push.model.DeviceTypeData;
import com.urbanairship.api.push.model.PushPayload;
import com.urbanairship.api.push.model.audience.Selectors;
import com.urbanairship.api.push.model.notification.Notifications;

import org.apache.log4j.BasicConfigurator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class PushExample {

   private static final Logger logger = LoggerFactory.getLogger("com.urbanairship.api");

   public void sendPush() {
       String appKey = "applicationKey";
       String appSecret = "applicationMasterSecret";

       // Step 1: Build and configure an UrbanAirshipClient
       UrbanAirshipClient client = UrbanAirshipClient.newBuilder()
               .setKey(appKey)
               .setSecret(appSecret)
               .build();

       // Step 2: Setup a payload for the message you want to send, and create the
       // push request.
       PushPayload payload = PushPayload.newBuilder()
           .setAudience(Selectors.all())
           .setNotification(Notifications.alert("A broadcast message"))
           .setDeviceTypes(DeviceTypeData.all())
           .build();

       PushRequest request = PushRequest.newRequest(payload);

       // Step 3: Use the client to execute the request, and try/catch for any issues, any
       // non-200 response, or non-library-related exceptions.
       try {
           Response<PushResponse> response = client.execute(request);
           logger.debug(String.format("Response %s", response.toString()));
       } catch (IOException e) {
           logger.error("IOException in API request " + e.getMessage());
       }

       // Cleanup: Close the HTTP client's thread pool.
       client.close();
   }

   public static void main(String args[]) {
      BasicConfigurator.configure();
      logger.debug("Starting test push");
      PushExample example = new PushExample();
      example.sendPush();
   }

}
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.all
push.notification = UA.notification(alert: 'A broadcast message')
push.device_types = UA.all
push.send_push

Send a push notification to all devices.

Push to Platform

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": "all",
          "notification": { "alert" : "Hey Android and iOS!!" },
          "device_types": ["android","ios"]
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.all_
push.notification = ua.notification(alert='Hey Android and iOS!!')
push.device_types = ua.device_types('android', 'ios')
push.send()
PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.all())
      .setNotification(Notifications.alert("Hey Android and iOS!!"))
      .setDeviceTypes(DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID))
      .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.all
push.notification = UA.notification(alert: 'Hey Android and iOS!!')
push.device_types = UA.device_types(['ios','android'])
push.send_push

You can send a push notification to a specific platform. This example sends a message to iOS and Android devices.

Push to Device Identifiers

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": {
             "OR": [
                {"ios_channel": "<iosChannel1>"},
                {"ios_channel": "<iosChannel2>"},
                {"ios_channel": "<iosChannel3>"}
             ]
          },
          "notification": { "alert" : "This goes to three iOS devices" },
          "device_types": ["ios"]
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.or_( ua.ios_channel('iosChannel1')
                      , ua.ios_channel('iosChannel2')
                      , ua.ios_channel('iosChannel3'))
push.notification = ua.notification('This goes to three iOS devices')
push.device_types = ua.device_types('ios')
push.send()
PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.iosChannels("<iosChannel1>", "<iosChannel2>", "<iosChannel3>"))
      .setNotification(Notifications.alert("This goes to three iOS devices"))
      .setDeviceTypes(DeviceTypeData.of(DeviceType.IOS))
      .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.or( UA.ios_channel('iosChannel1'),
                       UA.ios_channel('iosChannel2'),
                       UA.ios_channel('iosChannel3'))
push.notification = UA.notification(alert: 'This goes to three iOS devices')
push.device_types = UA.device_types(['ios'])
push.send_push

If you would like to target specific users, you can push to device identifiers. This example sends a message to several iOS channels.

 

 

 

 

 

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": {
             "OR": [
                {"android_channel": "<androidChannel1>"},
                {"android_channel": "<androidChannel2>"}
             ]
          },
          "notification": {
             "alert": "Hi Android users!"
          },
          "device_types": ["android"]
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.or_( ua.android_channel('androidChannel1')
                      , ua.android_channel('androidChannel2'))
push.notification = ua.notification('Hi Android users!')
push.device_types = ua.device_types('android')
push.send()
PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.androidChannels("<androidChannel1>", "<androidChannel2>"))
      .setNotification(Notifications.alert("Hi Android users!"))
      .setDeviceTypes(DeviceTypeData.of(DeviceType.ANDROID))
      .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.or( UA.android_channel('androidChannel1'),
                       UA.android_channel('androidChannel2'))
push.notification = UA.notification(alert: 'Hi Android users!')
push.device_types = UA.device_types(['android'])
push.send_push

The example above uses a segment that goes out to any device with one of the three iOS channels. You can also push to specific Android devices by replacing ios_channel with android_channel, and switching the device_type to android.

Push to Named User

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": { "named_user" : "user-id-1234" },
          "notification": { "alert" : "Hey named user!" },
          "device_types": ["android","ios"]
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.named_user('user-id-1234')
push.notification = ua.notification(alert='Hey named user!')
push.device_types = ua.device_types('android', 'ios')
push.send()
import com.urbanairship.api.push.PushRequest;
import com.urbanairship.api.push.model.DeviceType;
import com.urbanairship.api.push.model.DeviceTypeData;
import com.urbanairship.api.push.model.PushPayload;
import com.urbanairship.api.push.model.PushResponse;
import com.urbanairship.api.push.model.audience.Selectors;
import com.urbanairship.api.push.model.notification.Notifications;

PushPayload payload = PushPayload.newBuilder()
        .setAudience(Selectors.namedUser("user-id-1234"))
        .setNotification(Notifications.alert("Hey named user!"))
        .setDeviceTypes(DeviceTypeData.of(DeviceType.ANDROID, DeviceType.IOS))
        .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.named_user('user-id-1234')
push.notification = UA.notification(alert: 'Hey named user!')
push.device_types = UA.device_types(['android','ios'])
push.send_push

You may associate multiple Channel IDs with a single Named User ID, and when you push to a Named User ID we will send to each device associated with that Named User ID.

Push to Tag

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": {
             "AND": [
                {"tag": "breakingnews"},
                {"OR": [
                   {"tag": "sports"},
                   {"tag": "worldnews"}
                ]}
             ]
          },
          "notification": {
             "alert": "BREAKING: Important news is happening"
          },
          "device_types": "all"
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.and_(
   ua.tag('breakingnews'),
   ua.or_(
      ua.tag('sports'),
      ua.tag('worldnews')
   )
)
push.notification = ua.notification(alert='BREAKING: Important news is happening')
push.device_types = ua.all_
push.send()
import com.urbanairship.api.push.model.audience.Selector;

Selector orSelector = Selectors.tags("sports", "worldnews");
Selector bnewsSelector = Selectors.tag("breakingnews");
Selector compound = Selectors.and(orSelector, bnewsSelector);

PushPayload payload = PushPayload.newBuilder()
      .setAudience(compound)
      .setNotification(Notifications.alert("BREAKING: Important news is happening"))
      .setDeviceTypes(DeviceTypeData.all())
      .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.and(UA.tag('breakingnews'), UA.or(UA.tag('sports'), UA.tag('worldnews')))
push.notification = UA.notification(alert: 'BREAKING: Important news is happening')
push.device_types = UA.all
push.send_push

You can send pushes to devices with certain tags. In this example we send a message to devices that have the tags breakingnews and sports, or the tags breakingnews and worldnews.

 

 

 

 

 

 

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": {
             "AND": [
                { "tag": "sports", "group": "device" },
                { "tag": "gold", "group": "loyalty" }
             ]
          },
          "notification": {
             "alert": "BREAKING: Important news is happening"
          },
          "device_types": "all"
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.and_( {'tag': 'sports','group': 'device'}
                       , {'tag': 'gold', 'group': 'loyalty'})
push.notification = ua.notification(alert='BREAKING: Important news is happening')
push.device_types = ua.all_
push.send()
import com.urbanairship.api.push.model.audience.Selector;

Selector sports = Selectors.tagWithGroup("sports", "device");
Selector gold = Selectors.tagWithGroup("gold", "loyalty");
Selector compound = Selectors.and(sports, gold);

PushPayload payload = PushPayload.newBuilder()
      .setAudience(compound)
      .setNotification(Notifications.alert("BREAKING: Important news is happening"))
      .setDeviceTypes(DeviceTypeData.all())
      .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.and(UA.tag('sports', group:'device'), UA.tag('gold', group:'loyalty'))
push.notification = UA.notification(alert: 'BREAKING: Important news is happening')
push.device_types = UA.all
push.send_push

Pushing to a tag contained in a specific Tag Group is similarly easy.

 

 

 

 

 

 

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": { "tag": "America/Los_Angeles", "group": "timezone" },
          "notification": {
             "alert": "BREAKING: Important news is happening"
          },
          "device_types": "all"
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = {'tag': 'America/Los_Angeles','group': 'timezone'}
push.notification = ua.notification(alert='BREAKING: Important news is happening')
push.device_types = ua.all_
push.send()
import com.urbanairship.api.push.model.audience.Selector;

Selector tz = Selectors.tagWithGroup("America/Los_Angeles", "timezone");

PushPayload payload = PushPayload.newBuilder()
      .setAudience(tz)
      .setNotification(Notifications.alert("BREAKING: Important news is happening"))
      .setDeviceTypes(DeviceTypeData.all())
      .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.and(UA.tag('America/Los_Angeles', group:'timezone'))
push.notification = UA.notification(alert: 'BREAKING: Important news is happening')
push.device_types = UA.all
push.send_push

You can also push to a Device Property Tag. Device Property Tags are automatically generated by Urban Airship. For a list of available Device Property Tags, please see our reference document.

Push to Segment

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": { "segment": "<SegmentID>" },
          "notification": { "alert": "What up segment?" },
          "device_types": "all"
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.segment('segmentID')
push.notification = ua.notification(alert='What up segment?')
push.device_types = ua.all_
push.send()
// Set up a payload for the message you want to send
PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.segment("<SegmentID>"))
      .setNotification(Notifications.alert("What up segment?"))
      .setDeviceTypes(DeviceTypeData.all())
      .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.segment('segmentID')
push.notification = UA.notification(alert: "What up segment?")
push.device_types = UA.all
push.send_push

For details on creating, deleting, or getting information on segments, please see our Segments Builder Tutorial.

Push to Web

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience" : {
              "channel" : "2a243893-57f9-41d9-ac6b-1eb600b19bb2"
          },
          "notification": {
               "alert" : "A Web Notify message",
                "web": {
                    "title": "This is a title",
                    "icon": {
                        "url": "https://example.com/icon.png"
                    }
                }
          },
          "device_types": ["web"]
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.channel('2a243893-57f9-41d9-ac6b-1eb600b19bb2')
push.notification = ua.notification(
    alert='A Web Notify message',
    web=ua.web(
        icon={
        'url': 'https://example.com/icon.png'
        },
    title='This is a title',
    extra={'article_id': '12345'}
    )
)
push.device_types = ua.device_types('web')
push.send()
import com.urbanairship.api.push.model.notification.web.WebIcon;
import com.urbanairship.api.push.model.notification.web.WebDevicePayload;

WebIcon webIcon = WebIcon.newBuilder()
                .setUrl("https://example.com/icon.png")
                .build();

WebDevicePayload webPayload = WebDevicePayload.newBuilder()
                .setAlert("A Web Notify message")
                .setTitle("This is a title")
                .addExtraEntry("article_id", "12345")
                .setWebIcon(webIcon)
                .build();

PushPayload payload = PushPayload.newBuilder()
                .setAudience(Selectors.channel("2a243893-57f9-41d9-ac6b-1eb600b19bb2"))
                .setNotification(Notifications.notification(webPayload))
                .setDeviceTypes(DeviceTypeData.of(DeviceType.WEB))
                .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
#  Web Notify is not currently supported by the Ruby library.

Sending a push notification to a web device, i.e., a web browser, is like sending to any mobile platform. Simply provide the channel identifier and use the web object platform override for web-specific attributes.

Scheduled Push

curl https://go.urbanairship.com/api/schedules \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "name": "Baseball fans",
          "schedule": { "scheduled_time" : "2017-02-16T10:30:00" },
          "push": {
             "audience": { "tag": "usa" },
             "notification": { "alert": "Guess what day it is!" },
             "device_types": "all"
          }
       }'
import urbanairship as ua
import datetime

airship = ua.Airship('app_key', 'master_secret')
sched = airship.create_scheduled_push()
sched.name = 'Baseball fans'
sched.schedule = ua.scheduled_time(
   datetime.datetime(2017, 2, 16, 10, 30)
)
sched.push = airship.create_push()
sched.push.audience = ua.tag('usa')
sched.push.notification = ua.notification(alert='Guess what day it is!')
sched.push.device_types = ua.all_
sched.send()
import org.joda.time.DateTime;
import com.urbanairship.api.schedule.model.Schedule;
import com.urbanairship.api.schedule.ScheduleRequest;
import com.urbanairship.api.schedule.model.ScheduleResponse;

PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.tag("usa"))
      .setNotification(Notifications.alert("Guess what day it is!"))
      .setDeviceTypes(DeviceTypeData.all())
      .build();

DateTime dt = new DateTime(2017, 10, 27, 21, 47, 0, DateTimeZone.UTC);

Schedule schedule = Schedule.newBuilder()
      .setScheduledTimestamp(dt)
      .build();

ScheduleRequest request = ScheduleRequest.newRequest(schedule, payload);
Response<ScheduleResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.tag('usa')
push.notification = UA.notification(alert: 'Guess what day it is!')
push.device_types = UA.all

sched = airship.create_scheduled_push
sched.push = push
sched.name = 'Baseball fans'
sched.schedule = UA.scheduled_time(Time.new(2017, 2, 16, 10, 30))
sched.send_push

If you are scheduling a push to go out at a future time, i.e., not immediately, use the /api/schedules/ endpoint and include at least one Schedule Object.

For more information on scheduling pushes, please see Schedule a Notification.

A/B Tests

A/B Tests use the experiments API end point.

Create Experiment

curl "https://go.urbanairship.com/api/experiments" \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "name" : "Test Alerts",
          "audience" : { "named_user" : "user-id-1234" },
          "device_types" : ["android","ios"],
          "variants" : [{
            "push" : {
              "notification" : {
                "alert" : "Hello there!"
              }
            },
            "schedule" : { "scheduled_time" : "2017-11-16T22:44:00" }
          },
          {
            "push" : {
                "notification" : {
                  "alert" : "Greetings!"
                }
              },
            "schedule" : { "scheduled_time" : "2017-11-16T22:44:00" }
          }]
       }'
# The Experiments API is not currently supported by the Python library.
import com.urbanairship.api.experiments.ExperimentRequest;
import com.urbanairship.api.experiments.model.Experiment;
import com.urbanairship.api.experiments.model.ExperimentResponse;
import com.urbanairship.api.experiments.model.Variant;
import com.urbanairship.api.experiments.model.VariantPushPayload;
import com.urbanairship.api.push.model.DeviceType;
import com.urbanairship.api.push.model.DeviceTypeData;
import com.urbanairship.api.push.model.audience.Selectors;
import com.urbanairship.api.push.model.notification.Notification;
import com.urbanairship.api.schedule.model.Schedule;
import org.apache.log4j.BasicConfigurator;

DateTime dt = new DateTime(2017, 11, 16, 22, 44, 0, DateTimeZone.UTC);
Schedule schedule = Schedule.newBuilder()
        .setScheduledTimestamp(dt)
        .build();

Variant variantOne = Variant.newBuilder()
        .setPushPayload(VariantPushPayload.newBuilder()
                .setNotification(Notification.newBuilder()
                        .setAlert("Hello there!")
                        .build()
                )
                .build())
        .setSchedule(schedule)
        .build();

Variant variantTwo = Variant.newBuilder()
        .setPushPayload(VariantPushPayload.newBuilder()
                .setNotification(Notification.newBuilder()
                        .setAlert("Greetings!")
                        .build()
                )
                .build())
        .setSchedule(schedule)
        .build();

Experiment experiment = Experiment.newBuilder()
        .setName("Test Alerts")
        .setDescription("Test which alert is more popular.")
        .setDeviceTypes(DeviceTypeData.of(DeviceType.ANDROID, DeviceType.IOS))
        .setAudience(Selectors.namedUser("user-id-1234"))
        .addVariant(variantOne)
        .addVariant(variantTwo)
        .build();

ExperimentRequest request = ExperimentRequest.newRequest(experiment);
Response<ExperimentResponse> response = client.execute(request);
# The Experiments API is not currently supported by the Ruby library.

This example creates an experiment with two variants that schedules the A/B Test push on November 16, 2017 at 22:44:00 UTC for Android and iOS devices associated with the named user user-id-1234.

Delete Experiment

curl "https://go.urbanairship.com/api/experiments/scheduled/<experiment_id>" \
   -X DELETE \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json"
# The Experiments API is not currently supported by the Python library.
import com.urbanairship.api.experiments.ExperimentDeleteRequest;
import com.urbanairship.api.experiments.model.ExperimentResponse;

ExperimentDeleteRequest request = ExperimentDeleteRequest.newRequest("experiment_id");
Response<ExperimentResponse> response = client.execute(request);
# The Experiments API is not currently supported by the Ruby library.

This example deletes a scheduled experiment with the ID experiment_id. Note that experiments can only be deleted before they start.

Automation

Automated messages are handled via the pipelines API. Broadly, a request to the pipelines API must contain outcome and enabled attributes, and a trigger. The trigger specifies what sets off the automated messsage, and the outcome attribute specifies what happens once the message has been triggered. enabled is a boolean that specifies whether the automated message is active or not.

Tag Trigger

curl https://go.urbanairship.com/api/pipelines \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "name": "shoe buyer",
          "enabled": true,
          "immediate_trigger": { "tag_added": "bought-shoes" },
          "outcome": {
             "push": {
                "audience": "triggered",
                "notification": { "alert": "Heard you like shoes" },
                "device_types": "all"
             }
          }
       }'
# The Automation API is not currently supported by the Python library.
// The Automation API is not currently supported by the Java library.
# The Automation API is not currently supported by the Ruby library.

This request creates an automated message that sends when the tag bought-shoes is added to a device.

Tag Trigger and Delay

curl https://go.urbanairship.com/api/pipelines \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "name": "shoe buyer",
          "enabled": true,
          "immediate_trigger": { "tag_added" : "bought-shoes" },
          "outcome": {
             "delay": 3600,
             "push": {
                "audience": "triggered",
                "notification": { "alert": "Heard you like shoes" },
                "device_types": "all"
             }
          }
       }'
# The Automation API is not currently supported by the Python library.
// The Automation API is not currently supported by the Java library.
# The Automation API is not currently supported by the Ruby library.

This request is identical to the previous one, except we now add the delay attribute.

Once a device is tagged with bought-shoes, this automated message will send after a 60 minute delay.

First Open Trigger

curl https://go.urbanairship.com/api/pipelines \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "enabled": true,
          "immediate_trigger": "first_open",
          "outcome": {
             "delay": 3600,
             "push": {
                "audience": "triggered",
                "notification": { "alert" : "Thanks for downloading our app!" },
                "device_types": "all"
             }
          }
       }'
# The Automation API is not currently supported by the Python library.
// The Automation API is not currently supported by the Java library.
# The Automation API is not currently supported by the Ruby library.

This request creates an automated message with a First Open trigger.

List Enabled Pipelines

curl "https://go.urbanairship.com/api/pipelines?enabled=true" \
   -u "<AppKey>:<MasterSecret>"
# The Automation API is not currently supported by the Python library.
// The Automation API is not currently supported by the Java library.
# The Automation API is not currently supported by the Ruby library.

This request displays all automated messages that are currently active.

If you would like to see inactive automated messages, change enabled=true to enabled=false.

Tags

Channel Tag Operations

These examples use the /api/channels/tags endpoint to add, remove, and set tags on devices. Each example incorporates new Tag Group functionality as well.

For more information about Tag Groups and Mobile Data Bridge, please see the Mobile Data Bridge Primer and Tag Groups Walkthrough.

Add Tags

curl https://go.urbanairship.com/api/channels/tags \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
         "audience": {
            "ios_channel": "ios_channel_id",
            "android_channel": "android-channel-id"
         },
         "add": {
            "crm": ["partner_offers", "new_customer"]
         }
      }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
channel_tags = ua.devices.ChannelTags(airship)
ios_audience = 'ios_channel_id'
android_audience = 'android_channel_id'
channel_tags.set_audience(ios_audience, android_audience)
channel_tags.add('crm', ['partner_offers', 'new_customer'])
channel_tags.send()
import java.util.Set;
import java.util.HashSet;
import com.urbanairship.api.channel.ChannelTagRequest;

Set<String> addTags = new HashSet<String>();
addTags.add("partner_offers");
addTags.add("new_customer");

ChannelTagRequest request = ChannelTagRequest.newRequest()
    .addIOSChannels("ios_channel_id")
    .addAndroidChannel("android_channel_id")
    .addTags("crm", addTags);

Response<String> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

channel_tags = UA::ChannelTags.new(client: airship)
ios_audience = 'ios_channel_id'
android_audience = 'android_channel_id'
channel_tags.set_audience(
   ios: ios_audience,
   android: android_audience
)
channel_tags.add(group_name: 'crm', tags: ['partner_offers', 'new_customer'])
channel_tags.send_request

This example adds partner_offers and new_customer tags of the crm group to the iOS and Android channel.

 

 

 

 

Remove Tags

curl https://go.urbanairship.com/api/channels/tags \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
         "audience": {
            "ios_channel": "ios_channel_id"
         },
         "remove": {
            "crm": ["new_customer"]
         }
      }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
channel_tags = ua.devices.ChannelTags(airship)
ios_audience = 'ios_channel_id'
channel_tags.set_audience(ios_audience)
channel_tags.remove('crm', 'new_customer')
channel_tags.send()
import java.util.Set;
import java.util.HashSet;
import com.urbanairship.api.channel.ChannelTagRequest;

Set<String> removeTags = new HashSet<String>();
removeTags.add("new_customer");

ChannelTagRequest request = ChannelTagRequest.newRequest()
    .addIOSChannels("ios_channel_id")
    .removeTags("crm", removeTags);

Response<String> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

channel_tags = UA::ChannelTags.new(client: airship)
ios_audience = 'ios_channel_id'
channel_tags.set_audience(
   ios: ios_audience
)
channel_tags.remove(group_name: 'crm', tags: 'new_customer')
channel_tags.send_request

This example removes the new_customer tag of the crm group from the iOS channel.

 

 

 

 

Set Tags

curl https://go.urbanairship.com/api/channels/tags \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
         "audience": {
            "ios_channel": "ios_channel_id"
         },
         "set": {
            "crm": ["vip_offers"]
         }
      }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
channel_tags = ua.devices.ChannelTags(airship)
ios_audience = 'ios_channel_id'
channel_tags.set_audience(ios_audience)
channel_tags.set('crm', 'vip_offers')
channel_tags.send()
import java.util.Set;
import java.util.HashSet;
import com.urbanairship.api.channel.ChannelTagRequest;

Set<String> tags = new HashSet<String>();
tags.add("vip_offers");

ChannelTagRequest request = ChannelTagRequest.newRequest()
    .addIOSChannels("ios_channel_id")
    .setTags("crm", tags);

Response<String> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

channel_tags = UA::ChannelTags.new(client: airship)
ios_audience = 'ios_channel_id'
channel_tags.set_audience(
   ios: ios_audience
)
channel_tags.set(group_name: 'crm', tags: 'vip_offers')
channel_tags.send_request

This example sets the vip_offers tag of the crm group to the iOS channel, and any previously set tags of the crm group will be removed.

Legacy Tag Operations

The examples here use the legacy /api/tags/ endpoint. If you are using this endpoint, we strongly recommend transitioning to an implementation that uses either the Channels or Named Users tag endpoints.

List Tags

Tag Listing will return up to the first 100 tags per application.

curl https://go.urbanairship.com/api/tags/ \
   -X GET \
   -u "<AppKey>:<MasterSecret>"
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
list_tags = ua.TagList(airship)
list_tags.list_tags()
// The legacy tag API is not supported by the Java Library.
# The tags API is not currently supported by the Ruby library.

This request lists tags associated with a specific app key.

Create Tag

curl https://go.urbanairship.com/api/tags/pizza_yolo \
   -X PUT \
   -u "<AppKey>:<MasterSecret>"
# The tag creation endpoint is not supported by the Python library.
// The legacy tag API is not supported by the Java Library.
# The tags API is not currently supported by the Ruby library.

This request creates the pizza_yolo tag.

Add or Remove Devices from a Tag

If you are currently using the SDK to set tags, using this endpoint to add additional tags will result in the SDK immediately clearing the tags upon registration. See: Caution: Setting Tags From Different Sources.

curl https://go.urbanairship.com/api/tags/pizza_yolo \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "ios_channels": {
             "add": [
                "<iosChannel1>",
                "<iosChannel2>"
             ]
          },
          "android_channels": {
             "remove": [
                "<androidChannel1>",
                "<androidChannel2>",
                "<androidChannel3>"
             ]
          }
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
devices = ua.Tag(airship, 'pizza_yolo')
devices.add(
   ios_channels = ['ios_channel_1', 'ios_channel_2']
)
devices.remove(
   android_channels = ['android_channel_1', 'android_channel_2', 'android_channel_3']
)
// The legacy tag API is not supported by the Java Library.
# The tags API is not currently supported by the Ruby library.

This request removes the tag pizza_yolo from three Android devices and adds it to two iOS devices.

 

 

 

 

 

Delete Tag

curl https://go.urbanairship.com/api/tags/pizza_yolo \
   -X DELETE \
   -u "<AppKey>:<MasterSecret>"
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
delete_tag = ua.DeleteTag(airship, 'pizza_yolo')
delete_tag.send_delete()
// The legacy tag API is not supported by the Java Library.
# The tags API is not currently supported by the Ruby library.

This request deletes the tag pizza_yolo and removes it from all devices.

Batch Modification of Tags

{
   "<Device_ID>": "...",
   "tags": ["tag_1", ..., "tag_n"]
}

The batch endpoint takes an array of device identifier and tag array pairs.

 

curl https://go.urbanairship.com/api/tags/batch \
  -X PUT \
  -u "<AppKey>:<MasterSecret>" \
  -H "Accept: application/vnd.urbanairship+json; version=3" \
  -H "Content-Type: application/json" \
  -d '[
         {
            "ios_channel": "<iosChannel1>",
            "tags": [
               "birds",
               "puppies"
            ]
         },
         {
            "ios_channel": "<iosChannel2>",
            "tags": [
               "san_francisco",
               "shoes"
            ]
         },
         {
            "android_channel": "<androidChannel1>",
            "tags": [
               "world_news",
               "sports"
            ]
         }
      ]'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
send_batch = ua.BatchTag(airship)
send_batch.add_ios_channel('ios_channel_1', ['birds', 'puppies'])
send_batch.add_ios_channel('ios_channel_2', ['san_francisco', 'shoes'])
send_batch.add_android_channel('android_channel_1', ['world_news', 'sports'])
send_batch.send_request()
// The legacy tag API is not supported by the Java Library.
# The tags API is not currently supported by the Ruby library.

For each of these pairs, the API will verify that a list of tags is present and that the device ID is valid. The set of tags for the given device ID will be set to the given list of tags.

Message Center

The process for sending a Message Center message is similar to sending a standard notification, except now you must include a message object with the JSON payload, and the message object must contain title and body attributes. Together, these two attributes define your Message Center message. Additionally, there are a number of optional attributes. Please see the Message Center documentation for the full reference.

You’ll notice that device_types is set to one or more of iOS, Amazon, and Android for every example. Message Center is not supported on WNS, so attempting to push to WNS will result in an error message.

Standard Broadcast

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": "all",
          "notification": { "alert" : "You have a Message Center message omg!" },
          "device_types": ["ios", "android", "amazon"],
          "message": {
             "title": "Message Title",
             "body": "Here is the content of your message",
             "content_type": "text/html"
          }
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.all_
push.message = ua.message(
   title='Message Title',
   body='Here is the content of your message',
   content_type='text/html'
)
push.notification = ua.notification(alert='You have a Message Center message omg!')
push.device_types = ua.device_types('ios', 'android', 'amazon')
push.send()
import com.urbanairship.api.push.model.notification.richpush.RichPushMessage;

// Create the Message Center message
RichPushMessage message = RichPushMessage.newBuilder()
      .setTitle("Message Title")
      .setBody("Here is the content of your message")
      .setContentType("text/html")
      .build();

// Set up a payload for the message you want to send
PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.all())
      .setMessage(message)
      .setNotification(Notifications.alert("You have a Message Center message omg!"))
      .setDeviceTypes(DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID, DeviceType.AMAZON))
      .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.all
push.notification = UA.notification(alert: 'You have a Message Center message omg!')
push.device_types = UA.device_types(['ios', 'android', 'amazon'])
push.message = UA.message(
   title: 'Message Title',
   body: 'Here is the content of your message'
)
push.send_push

Send a Message Center message to your entire audience.

The content_type attribute simply specifies the MIME type of the data in body. In fact, content_type defaults to text/html, so we could have omitted it in this example.

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": "all",
          "notification": { "alert" : "The standard alert" },
          "device_types": "all",
          "message": {
             "title": "Message Title",
             "body": "<html><h1>Headline</h1><p>We can <a href=\"http://urbanairship.com\">insert a link!</a></p></html>",
             "content_type": "text/html"
          }
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.all_
push.message = ua.message(
   title = 'Message Title',
   body = '<html><h1>Headline</h1><p>We can <a href=\'http://urbanairship.com\'>insert a link!</a></p></html>'
)
push.notification = ua.notification(alert='The standard alert')
push.device_types = ua.all_
push.send()
import com.urbanairship.api.push.model.notification.richpush.RichPushMessage;

// Create the Message Center message
RichPushMessage message = RichPushMessage.newBuilder()
      .setTitle("Message Title")
      .setBody("<html><h1>Headline</h1><p>We can <a href=\"http://urbanairship.com\">insert a link!</a></p></html>")
      .setContentType("text/html")
      .build();

// Set up a payload for the message you want to send
PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.all())
      .setMessage(message)
      .setNotification(Notifications.alert("The standard alert"))
      .setDeviceTypes(DeviceTypeData.all())
      .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.all
push.notification = UA.notification(alert: 'The standard alert')
push.device_types = UA.all
push.message = UA.message(
   title: 'Message Title',
   body: '<html><h1>Headline</h1><p>We can <a href="http://urbanairship.com">insert a link!</a></p></html>'
)
push.send_push

In this example, we include a link in the body of our Message Center message.

Broadcast With Embedded YouTube Video

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": "all",
          "notification": { "alert" : "A VIDEO in a Message Center message?! What will they think of next." },
          "device_types": ["ios", "android", "amazon"],
          "message": {
             "title": "Message Title",
             "body": "<html><h1>Headline</h1><iframe width=\"560\" height=\"315\" src=\"//www.youtube.com/embed/pAsk3U0veoI\" frameborder=\"0\" allowfullscreen></iframe></html>",
             "content_type": "text/html"
          }
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.all_
push.message = ua.message(
   title = 'Message Title',
   body =  '<html><h1>Headline</h1><iframe width=\'560\' height=\'315\' src=\'//www.youtube.com/embed/pAsk3U0veoI\' frameborder=\'0\' allowfullscreen></iframe></html>'
)
push.notification = ua.notification(alert='A VIDEO in a Message Center message?! What will they think of next.')
push.device_types = ua.device_types('ios', 'android', 'amazon')
push.send()
import com.urbanairship.api.push.model.notification.richpush.RichPushMessage;

// Create the Message Center message
RichPushMessage message = RichPushMessage.newBuilder()
      .setTitle("Message Title")
      .setBody("<html><h1>Headline</h1><iframe width=\"560\" height=\"315\" src=\"//www.youtube.com/embed/pAsk3U0veoI\" frameborder=\"0\" allowfullscreen></iframe></html>")
      .setContentType("text/html")
      .build();

// Set up a payload for the message you want to send
PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.all())
      .setMessage(message)
      .setNotification(Notifications.alert("A VIDEO in a Message Center message? What will they think of next."))
      .setDeviceTypes(DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID, DeviceType.AMAZON))
      .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.all
push.notification = UA.notification(alert: 'A VIDEO in a Message Center message?! What will they think of next.')
push.device_types = UA.device_types(['ios', 'android', 'amazon'])
push.message = UA.message(
   title: 'Message Title',
   body: '<html><h1>Headline</h1><iframe width="560" height="315" src="//www.youtube.com/embed/pAsk3U0veoI" frameborder="0" allowfullscreen></iframe></html>'
)
push.send_push

This example includes an embedded YouTube video in the body.

Actions

Add or Remove Tags

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": "all",
          "notification": {
             "alert": "Mayor uses fork to eat pizza, public outraged.",
             "actions": { "add_tag" : ["pizza", "news"] }
          },
          "device_types": ["ios", "android"]
       }'

# To remove tags, simply use the `remove_tag` attribute rather than the `add_tag` attribute.
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.all_
push.notification = ua.notification(
   alert='Mayor uses fork to eat pizza, public outraged.',
   actions=ua.actions(
      add_tag=['pizza', 'news']
   )
)
push.device_types = ua.device_types('ios', 'android')
push.send()

# To remove tags, simply use the `remove_tag` attribute rather than the `add_tag` attribute.
import com.urbanairship.api.push.model.notification.actions.Actions;
import com.urbanairship.api.push.model.notification.actions.AddTagAction;
import com.urbanairship.api.push.model.notification.actions.TagActionData;
import com.urbanairship.api.push.model.notification.Notification;

// Create the tag set
Set<String> tags = new HashSet<String>();
tags.add("pizza");
tags.add("news");

// Define the action
Actions addTagAction = Actions.newBuilder()
      .addTags(new AddTagAction(TagActionData.set(tags)))
      .build();

// Add addTagAction to your notification
Notification addTagNotification = Notification.newBuilder()
      .setActions(addTagAction)
      .setAlert("Mayor uses fork to eat pizza, public outraged.")
      .build();

// Set up a payload for the message you want to send
PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.all())
      .setNotification(addTagNotification)
      .setDeviceTypes(DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID))
      .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);

// To remove tags, create a removeTagAction and add this action in the notification.

// Define the action
//    Actions removeTagAction = Actions.newBuilder()
//            .removeTags(new RemoveTagAction(TagActionData.set(tags)))
//            .build();

// Add removeTagAction to your notification
//    Notification addTagNotification = Notification.newBuilder()
//            .setActions(removeTagAction)
//            .setAlert("Mayor uses fork to eat pizza, public outraged.")
//            .build();
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.all
push.device_types = UA.device_types(['ios', 'android'])
push.notification = UA.notification(
   alert: 'Mayor uses fork to eat pizza, public outraged.',
   actions: UA.actions(
      add_tag: ['pizza', 'news']
   )
)
push.send_push

If a user taps on this notification, it will add the tags pizza and news to their device.

Share Text

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": "all",
          "notification": {
             "alert": "Thank you for using our app. Tell your friends about us!",
             "actions": { "share": "BestApp9000 is the best app ever." }
          },
          "device_types": ["ios", "android"]
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.all_
push.notification = ua.notification(
   alert='Thank you for using our app. Tell your friends about us!',
   actions=ua.actions(
      share='BestApp9000 is the best app ever.'
   )
)
push.device_types = ua.device_types('ios', 'android')
push.send()
import com.urbanairship.api.push.model.notification.Notification;
import com.urbanairship.api.push.model.notification.actions.*;

// Define the action
Actions shareText = Actions.newBuilder()
      .setShare(new ShareAction("BestApp9000 is the best app ever"))
      .build();

// Build a notification w/ the above sharing action incorporated
Notification shareNotification = Notification.newBuilder()
      .setActions(shareText)
      .setAlert("Thank you for using our app. Tell your friends about us!")
      .build();

// Set up a payload for the message you want to send
PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.all())
      .setNotification(shareNotification)
      .setDeviceTypes(DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID))
      .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.all
push.device_types = UA.device_types(['ios', 'android'])
push.notification = UA.notification(
   alert: 'Thank you for using our app. Tell your friends about us!',
   actions: UA.actions(
      share: 'BestApp9000 is the best app ever.'
   )
)
push.send_push

This API request will send a push containing the share action.

In particular, this push will read “Thank you for using our app. Tell your friends about us!” If the user taps on the notification, they will be brought into the app of their choice, where they will have the option to share the text “BestApp9000 is the best app ever.”

Open an External URL

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": "all",
          "notification": {
             "alert": "Read some news or something.",
             "actions": {
                "open": {
                   "type": "url",
                   "content": "http://www.theatlantic.com"
                }
             }
          },
          "device_types": ["ios", android"]
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.all_
push.notification = ua.notification(
   alert='Read some news or something.',
   actions=ua.actions(
      open_={
         'type': 'url',
         'content': 'http://www.theatlantic.com'
      }
   )
)
push.device_types = ua.device_types('ios', 'android')
push.send()
import java.net.URI;

// Create a URI
URI atlantic = null;
try {
   atlantic = new URI("http://www.theatlantic.com");
} catch (Exception e) {
   System.out.println("URI Syntax Error: " + e.getMessage());
}

Actions openURL = Actions.newBuilder()
      .setOpen(new OpenExternalURLAction(atlantic))
      .build();

Notification actionNotification = Notification.newBuilder()
      .setActions(openURL)
      .setAlert("Read some news or something.")
      .build();

PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.all())
      .setNotification(actionNotification)
      .setDeviceTypes(DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID))
      .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.all
push.device_types = UA.device_types(['ios', 'android'])
push.notification = UA.notification(
   alert: 'Read some news or something',
   actions: UA.actions(
      open_: {
         type: 'url',
         content: 'http://www.theatlantic.com'
      }
   )
)
push.send_push

This example opens an external URL after the user taps the push.

Interactive Notifications

Follow and Unfollow

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
           "audience": "all",
           "notification": {
               "alert": "Portland expected to get 6 inches of snow tonight.",
               "interactive": {
                   "type": "ua_follow",
                   "button_actions": {
                       "follow": {
                           "add_tag": "pdx-snowstorm-2017"
                       }
                   }
               }
           },
           "device_types": ["android", "ios"]
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.all_
push.notification = ua.notification(
   alert = 'Portland expected to get 6 inches of snow tonight.',
   interactive = ua.interactive(
      type = 'ua_follow',
      button_actions = {
         'follow': ua.actions(add_tag='pdx-snowstorm-2017')
      }
   )
)
push.device_types = ua.device_types('android', 'ios')
push.send()
import com.urbanairship.api.push.model.notification.Interactive;
import com.google.common.collect.ImmutableMap;

Interactive interactive = Interactive.newBuilder()
      .setType("ua_follow")
      .setButtonActions(ImmutableMap.of(
            "follow",
            Actions.newBuilder()
               .addTags(new AddTagAction(TagActionData.single("pdx-snowstorm-2017")))
               .build()))
      .build();

Notification interactiveNotification = Notification.newBuilder()
      .setInteractive(interactive)
      .setAlert("Portland expected to get 6 inches of snow tonight.")
      .build();

PushPayload payload = PushPayload.newBuilder()
         .setAudience(Selectors.all())
         .setNotification(interactiveNotification)
         .setDeviceTypes(DeviceTypeData.of(DeviceType.ANDROID, DeviceType.IOS))
         .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.all
push.device_types = UA.device_types(['android', 'ios'])
push.notification = UA.notification(
   alert: 'Portland expected to get 6 inches of snow tonight.',
   interactive: UA.interactive(
      type: 'ua_follow',
      button_actions: {
         follow: { add_tag: 'pdx-snowstorm-2017' }
      }
   )
)
push.send_push

You can send an interactive notification that gives the user the option to follow a story. To do so, use the ua_follow interactive notification, and if a user selects the Follow button, add a tag that is relevant to the current story.

In this example, users who want more information about the weather can choose Follow, and the pdx-snowstorm-2017 tag will be added to their device.

 

 

 

 

 

 

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": { "tag": "pdx-snowstorm-2017" },
          "notification": {
             "alert": "Minor snow storm reduces Portland to post-apocalyptic wasteland.",
             "interactive": {
                "type": "ua_unfollow",
                "button_actions": {
                   "unfollow": {
                      "remove_tag": "pdx-snowstorm-2017"
                   }
                }
             }
          },
          "device_types": ["android", "ios"]
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.tag('pdx-snowstorm-2017')
push.notification = ua.notification(
   alert = 'Minor snow storm reduces Portland to post-apocalyptic wasteland.',
   interactive = ua.interactive(
      type = 'ua_unfollow',
      button_actions = {
         'unfollow': ua.actions(remove_tag='pdx-snowstorm-2017')
      }
   )
)
push.device_types = ua.device_types('android', 'ios')
push.send()
import com.urbanairship.api.push.model.notification.Interactive;
import com.google.common.collect.ImmutableMap;

Interactive interactive = Interactive.newBuilder()
      .setType("ua_unfollow")
      .setButtonActions(ImmutableMap.of(
            "unfollow",
            Actions.newBuilder()
               .removeTags(new RemoveTagAction(TagActionData.single("pdx-snowstorm-2017")))
               .build()))
      .build();

Notification interactiveNotification = Notification.newBuilder()
      .setInteractive(interactive)
      .setAlert("Minor snow storm reduces Portland to post-apocalyptic wasteland.")
      .build();

PushPayload payload = PushPayload.newBuilder()
         .setAudience(Selectors.tag("pdx-snowstorm-2017"))
         .setNotification(interactiveNotification)
         .setDeviceTypes(DeviceTypeData.of(DeviceType.ANDROID, DeviceType.IOS))
         .build();

PushRequest request = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

push = airship.create_push
push.audience = UA.tag('pdx-snowstorm-2017')
push.device_types = UA.device_types(['android', 'ios'])
push.notification = UA.notification(
   alert: 'Minor snow storm reduces Portland to post-apocalyptic wasteland.',
   interactive: UA.interactive(
      type: 'ua_unfollow',
      button_actions: {
         unfollow: { remove_tag: 'pdx-snowstorm-2017' }
      }
   )
)
push.send_push

Then, any follow-up notifications on this story should be pushed to the tag pdx-snowstorm-2017. Moreover, you can use the ua_unfollow built-in interactive notification to give users the option to unsubscribe from updates at any time. If a user chooses unfollow, the pdx-snowstorm-2017 tag is removed from their device.

Remind Me Later

There are two steps to creating an Interactive Notification with reminder functionality:

  1. Create an automated message containing your story reminder. This message should be triggered with a tag.
  2. Create an interactive notification that uses the ua_remind_me_later type, and have the Remind me later button set a tag that triggers the automated message.


curl https://go.urbanairship.com/api/pipelines \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "name": "pizza deal reminder",
          "enabled": true,
          "immediate_trigger": { "tag_added": "pizza-deal-reminder" },
          "outcome": {
             "delay": 86400,
             "push": {
                "audience": "triggered",
                "notification": { "alert": "have a slice on us! (terms and conditions apply)" },
                "device_types": "all"
             }
          }
       }'
# This example requires use of the Automation API, which is currently unsupported by the Python
# library.
// This example requires use of the Automation API, which is currently unsupported by the Java
// library
# This example requires use of the Automation API, which is currently unsupported by
# the Ruby library.

Beginning with step 1, this request creates an automated message that’s triggered once the pizza-deal-reminder tag is added to a user’s device.

The delay is critical here. If you don’t include a delay, the reminder notification will be sent immediately after the user hits Remind me later. In this payload, the delay is set to 86,400 seconds, or 24 hours.

 

 

 

 

curl https://go.urbanairship.com/api/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": "all",
          "notification": {
             "alert": "buy 100 pizzas, get a slice free!",
             "interactive": {
                "type": "ua_remind_me_later",
                "button_actions": {
                   "remind": {
                      "add_tag": "pizza-deal-reminder"
                   }
                }
             }
          },
          "device_types" : ["android", "ios"]
       }'
# This example requires use of the Automation API, which is currently unsupported by the Python
# library.
// This example requires use of the Automation API, which is currently unsupported by the Java
// library.
# This example requires use of the Automation API, which is currently unsupported by
# the Ruby library.

Once you have created the automated message, create an interactive notification that triggers the automated message by tagging users with pizza-story-reminder if they press the Remind me later button.

Reports

Push Sends Report

curl "https://go.urbanairship.com/api/reports/sends/?start=2017-10-1&end=2017-10-14&precision=DAILY" \
   -u "<AppKey>:<MasterSecret>"
import urbanairship as ua
from datetime import datetime

airship = ua.Airship('app_key', 'master_secret')
start_date = datetime(2017, 10, 1)
end_date = datetime(2017, 10, 14)
precision = 'DAILY'
listing = ua.reports.PushList(airship, start_date, end_date, precision)

for resp in listing:
  print(resp.date, resp.android, resp.ios)
import com.urbanairship.api.reports.PlatformStatsRequest;
import com.urbanairship.api.reports.PlatformStatsRequestType;
import com.urbanairship.api.reports.model.PlatformStatsResponse;
import com.urbanairship.api.reports.model.Precision;

DateTime start = new DateTime(2017, 10, 1, 0, 0, 0, 0);
DateTime end = start.plus(Period.days(14));

PlatformStatsRequest request = PlatformStatsRequest.newRequest(PlatformStatsRequestType.SENDS)
    .setStart(start)
    .setEnd(end)
    .setPrecision(Precision.DAILY);

Response<PlatformStatsResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

listing = UA::PushList.new(
   client: airship,
   start_date: '2017-10-01',
   end_date: '2017-10-14',
   precision: 'DAILY'
)
listing.each do |resp|
    puts(resp)
end

This request retrieves the Push Sends for the first two weeks of October 2017, with a daily precision.

Push Response Report

curl "https://go.urbanairship.com/api/reports/responses/?start=2017-10-1%2010:00&end=2017-10-14%2020:00&precision=DAILY" \
   -u "<AppKey>:<MasterSecret>"
import urbanairship as ua
from datetime import datetime

airship = ua.Airship('app_key', 'master_secret')
start_date = datetime(2017, 10, 1)
end_date = datetime(2017, 10, 14)
precision = 'DAILY'
listing = ua.reports.ResponseReportList(
  airship,
  start_date,
  end_date,
  precision
)

for resp in listing:
  print(resp.date, resp.android['influenced'], resp.android['direct'],
      resp.ios['influenced'], resp.ios['direct'])
// The Push Response Report is not currently supported by the Java library.
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

listing = UA::ResponseReportList.new(
    client: airship,
    start_date: '2017-10-01',
    end_date: '2017-10-14',
    precision: 'DAILY'
)
listing.each do |resp|
    puts(resp)
end

This request retrieves the Push Response for the first two weeks of October 2017, with a daily precision.

Individual Push Response Statistics

curl "https://go.urbanairship.com/api/reports/responses/<push_id>" \
   -u "<AppKey>:<MasterSecret>"
import urbanairship as ua
airship = ua.Airship('appkey', 'master_secret')
stats = ua.reports.IndividualResponseStats(airship)
statistics = stats.get('push_id')
import com.urbanairship.api.reports.PushInfoRequest;
import com.urbanairship.api.reports.model.PushInfoResponse;
import java.util.UUID;
import org.joda.time.DateTime;

PushInfoRequest request = PushInfoRequest.newRequest("push_id");
Response<PushInfoResponse> response = client.execute(request);
PushInfoResponse pushInfo = response.getBody().get();

// Number of sends
int sends = pushInfo.getSends();
// Number of direct responses to the push
int directResponses = pushInfo.getDirectResponses();
// When the push was sent
DateTime date = pushInfo.getPushTime();
// The push type - can be one of BROADCAST_PUSH, SCHEDULED_PUSH, TAG_PUSH, UNICAST_PUSH
PushInfoResponse.PushType type = pushInfo.getPushType();
// The unique identifier for the push
UUID pushId = pushInfo.getPushId();
require 'urbanairship'
UA = Urbanairship
airship = UA::Client.new(key: 'application_key', secret: 'master_secret')
stats = UA::IndividualResponseStats.new(client: airship)
statistics = stats.get(push_id: 'push_id')

This request retrieves the detailed reports information about a specific push notification. The push_id is the identifier returned by the API that represents a specific push message delivery.

Response Listing

curl "https://go.urbanairship.com/api/reports/responses/list?start=2017-10-01%2010:00&end=2017-10-14%2020:00" \
   -u "<AppKey>:<MasterSecret>"
import urbanairship as ua
from datetime import datetime

airship = ua.Airship('app_key', 'master_secret')
start_date = datetime(2017, 10, 1)
end_date = datetime(2017, 10, 14)
response_list = ua.reports.ResponseList(airship, start_date, end_date)

for response in response_list:
    print(response.push_uuid, response.push_time, response.push_type,
        response.direct_responses, response.sends)
import org.joda.time.Period;
import com.urbanairship.api.reports.PushListingRequest;
import com.urbanairship.api.reports.model.PushListingResponse;

DateTime start = new DateTime(2017, 10, 1, 12, 0, 0, 0);
DateTime end = start.plus(Period.days(14));

PushListingRequest request = PushListingRequest.newRequest()
        .setStart(start)
        .setEnd(end);

Response<PushListingResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

response_list = UA::ResponseList.new(
   client: airship,
   start_date: '2017-10-01',
   end_date: '2017-10-15',
   limit: 20,
   push_id_start: 'start_id'
)
response_list.each do |resp|
   puts(resp)
end

This request lists all pushes, plus associated basic information, in the given timeframe.

App Opens Report

curl "https://go.urbanairship.com/api/reports/opens/?start=2017-10-1%2010:00&end=2017-10-14%2020:00&precision=HOURLY" \
   -u "<AppKey>:<MasterSecret>"
import urbanairship as ua
from datetime import datetime

airship = ua.Airship('appkey', 'master_secret')
start_date = datetime(2017, 10, 1)
end_date = datetime(2017, 10, 14)
precision = 'HOURLY'
listing = ua.reports.AppOpensList(airship, start_date, end_date, precision)

for resp in listing:
  print(resp.date, resp.android, resp.ios)
import com.urbanairship.api.reports.PlatformStatsRequest;
import com.urbanairship.api.reports.PlatformStatsRequestType;
import com.urbanairship.api.reports.model.PlatformStatsResponse;
import com.urbanairship.api.reports.model.Precision;

DateTime start = new DateTime(2017, 10, 1, 0, 0, 0, 0);
DateTime end = start.plus(Period.days(14));

PlatformStatsRequest request = PlatformStatsRequest.newRequest(PlatformStatsRequestType.APP_OPENS)
    .setStart(start)
    .setEnd(end)
    .setPrecision(Precision.HOURLY);

Response<PlatformStatsResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

listing = UA::AppOpensList.new(
    client: airship,
    start_date: '2017-10-01',
    end_date: '2017-10-14',
    precision: 'HOURLY'
)
listing.each do |app_opens|
    puts(app_opens)
end

This request retrieves the App Opens for the first two weeks of October 2017, with an hourly precision.

Time in App Report

curl "https://go.urbanairship.com/api/reports/timeinapp/?start=2017-10-1&end=2017-10-14&precision=DAILY" \
   -u "<AppKey>:<MasterSecret>"
import urbanairship as ua
from datetime import datetime

airship = ua.Airship('app_key', 'master_secret')
start_date = datetime(2017, 10, 1)
end_date = datetime(2017, 10, 14)
precision = 'DAILY'
listing = ua.reports.TimeInAppList(airship, start_date, end_date, precision)

for resp in listing:
  print(resp.date, resp.android, resp.ios)
import com.urbanairship.api.reports.PlatformStatsRequest;
import com.urbanairship.api.reports.PlatformStatsRequestType;
import com.urbanairship.api.reports.model.PlatformStatsResponse;
import com.urbanairship.api.reports.model.Precision;

DateTime start = new DateTime(2017, 10, 1, 0, 0, 0, 0);
DateTime end = start.plus(Period.days(14));

PlatformStatsRequest request = PlatformStatsRequest.newRequest(PlatformStatsRequestType.TIME_IN_APP)
    .setStart(start)
    .setEnd(end)
    .setPrecision(Precision.DAILY);

Response<PlatformStatsResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

listing = UA::TimeInAppList.new(
    client: airship,
    start_date: '2017-10-01',
    end_date: '2017-10-14',
    precision: 'HOURLY'
)
listing.each do |time_in_app|
    puts(time_in_app)
end

This request retrieves the Time In App for the first two weeks of October 2017, with a daily precision.

Devices Report

curl "https://go.urbanairship.com/api/reports/devices/?date=2017-10-14" \
   -u "<AppKey>:<MasterSecret>"
import urbanairship as ua
from datetime import datetime

airship = ua.Airship('app_key', 'master_secret')
date = datetime(2017, 10, 14)
report = ua.reports.DevicesReport(airship)
devices = report.get(date)

print(devices)
// The Devices Report is not currently supported by the Java library.
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

devices_report = UA::DevicesReport.new(client: airship)
devices = devices_report.get(date: '2017-10-14')
print(devices)

The following request will retrieve the Devices Report up to October 14th.

Opt-in Report

curl "https://go.urbanairship.com/api/reports/optins/?start=2017-10-01%2010:00&end=2017-10-14%2020:00&precision=DAILY" \
   -u "<AppKey>:<MasterSecret>"
import urbanairship as ua
from datetime import datetime

airship = ua.Airship('app_key', 'master_secret')
start_date = datetime(2017, 10, 1)
end_date = datetime(2017, 10, 14)
precision = 'DAILY'
listing = ua.reports.OptInList(airship, start_date, end_date, precision)
for resp in listing:
    print(resp.date, resp.android, resp.ios)
import com.urbanairship.api.reports.PlatformStatsRequest;
import com.urbanairship.api.reports.PlatformStatsRequestType;
import com.urbanairship.api.reports.model.PlatformStatsResponse;
import com.urbanairship.api.reports.model.Precision;
import java.util.List;
import org.joda.time.Period;

DateTime start = new DateTime(2017, 10, 1, 0, 0, 0, 0);
DateTime end = start.plus(Period.days(14));

PlatformStatsRequest optInsRequest = PlatformStatsRequest.newRequest(PlatformStatsRequestType.OPT_INS)
    .setStart(start)
    .setEnd(end)
    .setPrecision(Precision.DAILY);

Response<PlatformStatsResponse> optInsResponse = client.execute(optInsRequest);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

listing = UA::OptInList.new(
    client: airship,
    start_date: '2017-10-01',
    end_date: '2017-10-14',
    precision: 'DAILY')
listing.each do |opt_ins|
    puts(opt_ins)
end

The following request will retrieve the number of opted-in Push users who accessed the app within the first two weeks of October 2017, with a daily precision.

Opt-out Report

curl "https://go.urbanairship.com/api/reports/optouts/?start=2017-10-01%2010:00&end=2017-10-14%2020:00&precision=DAILY" \
   -u "<AppKey>:<MasterSecret>"
import urbanairship as ua
from datetime import datetime

airship = ua.Airship('app_key', 'master_secret')
start_date = datetime(2017, 10, 1)
end_date = datetime(2017, 10, 14)
precision = 'DAILY'
listing = ua.reports.OptOutList(airship, start_date, end_date, precision)
for resp in listing:
    print(resp.date, resp.android, resp.ios)
import com.urbanairship.api.reports.PlatformStatsRequest;
import com.urbanairship.api.reports.PlatformStatsRequestType;
import com.urbanairship.api.reports.model.PlatformStatsResponse;
import com.urbanairship.api.reports.model.Precision;
import java.util.List;
import org.joda.time.Period;

DateTime start = new DateTime(2017, 10, 1, 0, 0, 0, 0);
DateTime end = start.plus(Period.days(14));

PlatformStatsRequest optOutsRequest = PlatformStatsRequest.newRequest(PlatformStatsRequestType.OPT_OUTS)
    .setStart(start)
    .setEnd(end)
    .setPrecision(Precision.DAILY);

Response<PlatformStatsResponse> optOutsResponse = client.execute(optOutsRequest);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

listing = UA::OptOutList.new(
    client: airship,
    start_date: '2017-10-01',
    end_date: '2017-10-14',
    precision: 'DAILY')
listing.each do |opt_outs|
    puts(opt_outs)
end

The following request will retrieve the number of opted-out Push users who accessed the app within the first two weeks of October 2017, with a daily precision.

Statistics

curl "https://go.urbanairship.com/api/push/stats/?start=2017-10-01&end=2017-10-01+12:00" \
   -u "<AppKey>:<MasterSecret>"
# The stats endpoint is not currently supported by the Python library.
import com.urbanairship.api.reports.StatisticsRequest;
import java.util.List;

DateTime start = new DateTime(2017, 10, 1, 0, 0, 0, 0);
DateTime end = start.plus(Period.hours(12));

StatisticsRequest request = StatisticsRequest.newRequest(start, end);

Response<List<StatisticsResponse>> response = client.execute(request);
# The stats endpoint is not supported by the Ruby library.

This request retrieves push statistics for the first 12 hours of October 1, 2017.

Segments

Retrieve Segment List

curl https://go.urbanairship.com/api/segments \
   -u "<AppKey>:<MasterSecret>" \
   -H "Content-Type: application/json" \
   -X GET
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
segment_list = ua.SegmentList(airship)

for segment in segment_list:
   print(segment.display_name)
import com.urbanairship.api.segments.SegmentListingRequest;
import com.urbanairship.api.segments.model.SegmentListingResponse;

SegmentListingRequest request = SegmentListingRequest.newRequest();
Response<SegmentListingResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

segment_list = UA::SegmentList.new(client: airship)
segment_list.each do |segment|
   puts(segment['display_name'])
end

This request returns a list of all segments associated with the given app key.

Get Segment Info

curl https://go.urbanairship.com/api/segments/<SegmentID> \
   -u "<AppKey>:<MasterSecret>" \
   -H "Content-Type: application/json" \
   -X GET
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
segment = ua.Segment()
segment.from_id(airship, 'segment_id')

print(segment.display_name, segment.criteria)
import com.urbanairship.api.segments.SegmentLookupRequest;
import com.urbanairship.api.segments.model.SegmentView;

SegmentLookupRequest request = SegmentLookupRequest.newRequest("<SegmentID>");
Response<SegmentView> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

segment = UA::Segment.new(client: airship)
segment.from_id(id: 'segment_id')

This request gives the information associated with a given <SegmentID>.

In particular, this request will return a JSON object with the segment criteria and display name.

Create a Segment

curl https://go.urbanairship.com/api/segments \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Content-Type: application/json" \
   -d '{
          "display_name": "Green",
          "criteria": {
             "and": [
                {"tag": "Yellow"},
                {"tag": "Blue"}
             ]
          }
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
segment = ua.Segment()
segment.display_name = 'Green'
segment.criteria = ua.and_(
   ua.tag('Yellow'),
   ua.tag('Blue')
)
segment.create(airship)
import com.urbanairship.api.push.model.audience.Selector;
import com.urbanairship.api.push.model.audience.Selectors;
import com.urbanairship.api.segments.SegmentRequest;

Selector andSelector = Selectors.tags("Yellow", "Blue");
SegmentRequest request = SegmentRequest.newRequest();
request.setCriteria(andSelector);
request.setDisplayName("Green");

Response<String> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

segment = UA::Segment.new(client: airship)
segment.display_name = 'Green'
segment.criteria = UA.and(UA.tag('Yellow'), UA.tag('Blue'))
segment.create

This request creates a segment with the display name “Green”, and it consists of users with both the tag “Yellow” and the tag “Blue”.

 

 

 

Create a Location-Based Segment

curl https://go.urbanairship.com/api/segments \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Content-Type: application/json" \
   -d '{
          "display_name": "san_francisco_dancers",
          "criteria": {
             "and": [
                {
                   "location": {
                      "id": "4oFkxX7RcUdirjtaenEQIV",
                      "date": {
                         "recent": {
                            "months": 3
                         }
                      }
                   }
               },
               { "tag": "dancer" }
             ]
          }
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
segment = ua.Segment()
segment.display_name = 'san_francisco_dancers'
segment.criteria = ua.and_(
   ua.location(
      id='4oFkxX7RcUdirjtaenEQIV',
      date=ua.recent_date(months=3)
   ),
   ua.tag('dancer')
)
segment.create(airship)
import com.urbanairship.api.push.model.audience.Selector;
import com.urbanairship.api.push.model.audience.Selectors;
import com.urbanairship.api.push.model.audience.location.DateRange;

Selector dancer = Selectors.tag("dancer");
DateRange dateRange = Selectors.months(3);
Selector location = Selectors.location("4oFkxX7RcUdirjtaenEQIV", dateRange);
Selector locationCriteria = Selectors.and(dancer, location);

SegmentRequest request = SegmentRequest.newRequest();
request.setCriteria(locationCriteria);
request.setDisplayName("san_francisco_dancers");

Response<String> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

segment = UA::Segment.new(client: airship)
segment.display_name = 'san_francisco_dancers'
segment.criteria = UA.and(
              UA.tag('dancer'),
              UA.location(id: '4oFkxX7RcUdirjtaenEQIV', date: UA.recent_date(months: 3))
              )
segment.create

This request creates a segment that consists of devices that:

  • Have been in San Francisco within the past three months.
  • Have the tag dancer.

 

 

 

 

 

 

Create a Segment with Audience Lists

While the Segment Builder does not currently work with Audience Lists, you can create segments that incorporate lists via the API.

Uploaded List
curl https://go.urbanairship.com/api/segments \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Content-Type: application/json" \
   -d '{
          "display_name": "weekly_circular_pizza",
          "criteria": {
             "and": [
                { "tag": "pizza" },
                { "static_list": "weekly_circular" }
             ]
          }
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
segment = ua.Segment()
segment.display_name = 'weekly_circular_pizza'
segment.criteria = ua.and_(
  {'tag': 'pizza'},
  {'static_list': 'weekly_circular'}
)
segment.create(airship)
import com.urbanairship.api.push.model.audience.Selector;
import com.urbanairship.api.push.model.audience.Selectors;
import com.urbanairship.api.segments.SegmentRequest;

Selector tag = Selectors.tag("pizza");
Selector uploadedAudiencelist = Selectors.staticList("weekly_circular");
Selector andSelector = Selectors.and(tag, uploadedAudiencelist);

SegmentRequest request = SegmentRequest.newRequest();
request.setCriteria(andSelector);
request.setDisplayName("weekly_circular_pizza");

Response<String> response = client.execute(request);
# Segment creation with audience lists is not currently supported by the Ruby library.

This example creates a segment that consists of devices on an uploaded weekly circular list with the tag "pizza".

 

 

 

Lifecycle List

Segments can also contain Lifecycle Lists. In this case, the static_list key should have one of our Lifecycle Lists as a value.

curl https://go.urbanairship.com/api/segments \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Content-Type: application/json" \
   -d '{
          "display_name": "last_app_open_7_pizza",
          "criteria": {
             "and": [
                { "tag": "pizza" },
                { "static_list": "ua_app_open_last_7_days" }
             ]
          }
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
segment = ua.Segment()
segment.display_name = 'last_app_open_7_pizza'
segment.criteria = ua.and_(
  {'tag': 'pizza'},
  {'static_list': 'ua_app_open_last_7_days'}
)
segment.create(airship)
import com.urbanairship.api.push.model.audience.Selector;
import com.urbanairship.api.push.model.audience.Selectors;
import com.urbanairship.api.segments.SegmentRequest;

Selector tag = Selectors.tag("pizza");
Selector uploadedAudiencelist = Selectors.staticList("ua_app_open_last_7_days");
Selector andSelector = Selectors.and(tag, uploadedAudiencelist);

SegmentRequest request = SegmentRequest.newRequest();
request.setCriteria(andSelector);
request.setDisplayName("last_app_open_7_pizza");

Response<String> response = client.execute(request);
# Segment creation with audience lists is not currently supported by the Ruby library.

This example creates a segment consisting of devices that:

  • Have the tag "pizza"
  • Have opened the app in the past 7 days

Delete a Segment

curl https://go.urbanairship.com/api/segments/<SegmentID> \
   -u "<AppKey>:<MasterSecret>" \
   -X DELETE
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
segment = ua.Segment()
segment.from_id(airship, 'segment_id')
segment.delete(airship)
import com.urbanairship.api.segments.SegmentDeleteRequest;

SegmentDeleteRequest request = SegmentDeleteRequest.newRequest("<SegmentID>");
Response<String> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

segment = UA::Segment.new(client: airship)
segment.from_id(id: 'segment_id')
segment.delete

This request deletes the segment associated with the given <SegmentID>.

Location

Get Location Boundary Information

There are several ways to get location boundary information.

By Name

curl https://go.urbanairship.com/api/location/?q=Chicago \
   -X GET \
   -u "<AppKey>:<MasterSecret>" \
   -H "Content-Type: application/json"
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
l = ua.LocationFinder(airship)
l.name_lookup('Chicago', 'city')
import com.urbanairship.api.location.LocationRequest;
import com.urbanairship.api.location.model.LocationResponse;

LocationRequest request = LocationRequest.newRequest("Chicago")
    .setType("city");
Response<LocationResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

location = UA::Location.new(client: airship)
location.name_lookup(name: 'Chicago', type: 'city')

 

 

By Latitude and Longitude

curl https://go.urbanairship.com/api/location/45.52,-122.681944?type=city \
   -X GET \
   -u "<AppKey>:<MasterSecret>" \
   -H "Content-Type: application/json"
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
l = ua.LocationFinder(airship)
l.coordinates_lookup(45.52, -122.681944, 'city')
import com.urbanairship.api.location.LocationRequest;
import com.urbanairship.api.location.model.LocationResponse;
import com.urbanairship.api.location.model.Point;

Point point = Point.newBuilder()
    .setLatitude(45.52)
    .setLongitude(-122.681944)
    .build();

LocationRequest request = LocationRequest.newRequest(point)
    .setType("city");
Response<LocationResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

location = UA::Location.new(client: airship)
location.coordinates_lookup(latitude: 45.52, longitude: -122.681944, type: 'city')

Note that the numbers are in the order latitude, longitude.

 

 

 

By Bounding Box

curl https://go.urbanairship.com/api/location/32.5343,-124.4096,42.0095,-114.1308?type=province
   -X GET \
   -u "<AppKey>:<MasterSecret>" \
   -H "Content-Type: application/json"
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
l = ua.LocationFinder(airship)
l.bounding_box_lookup(32.5343, -124.4096, 42.0095, -114.1308, 'province')
import com.urbanairship.api.location.LocationRequest;
import com.urbanairship.api.location.model.LocationResponse;
import com.urbanairship.api.location.model.Point;

Point cornerOne = Point.newBuilder()
    .setLatitude(32.5343)
    .setLongitude(-124.4096)
    .build();

Point cornerTwo = Point.newBuilder()
    .setLatitude(42.8781)
    .setLongitude(-114.1308)
    .build();

BoundedBox box = BoundedBox.newBuilder()
    .setCornerOne(cornerOne)
    .setCornerTwo(cornerTwo)
    .build();

LocationRequest request = LocationRequest.newRequest(box)
    .setType("province");
Response<LocationResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

location = UA::Location.new(client: airship)
location.bounding_box_lookup(lat1: 32.5343, long1: -124.4096,
  lat2: 42.0095, long2: -114.1308, type: 'province')

Named Users

Association

curl https://go.urbanairship.com/api/named_users/associate \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "channel_id": "89s3892b-0234-9023-d9a2-9023ad802a9s",
          "device_type": "ios",
          "named_user_id": "user-id-1234"
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
named_user = ua.NamedUser(airship, 'user-id-1234')
named_user.associate('89s3892b-0234-9023-d9a2-9023ad802a9s', 'ios')
import com.urbanairship.api.nameduser.NamedUserRequest;

NamedUserRequest request = NamedUserRequest.newAssociationRequest()
        .setChannel("89s3892b-0234-9023-d9a2-9023ad802a9s", ChannelType.IOS)
        .setNamedUserId("user-id-1234");

Response<String> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

named_user = UA::NamedUser.new(client: airship)
named_user.named_user_id = 'user-id-1234'
named_user.associate(channel_id: '89s3892b-0234-9023-d9a2-9023ad802a9s', device_type: 'ios')

This example associates the given channel with the named user id "user-id-1234".

Disassociation

curl https://go.urbanairship.com/api/named_users/disassociate \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "channel_id": "89s3892b-0234-9023-d9a2-9023ad802a9s",
          "device_type": "ios",
          "named_user_id": "user-id-1234"
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
named_user = ua.NamedUser(airship, 'user-id-1234')
named_user.disassociate('89s3892b-0234-9023-d9a2-9023ad802a9s', 'ios')
import com.urbanairship.api.nameduser.NamedUserRequest;

NamedUserRequest request = NamedUserRequest.newDisassociationRequest()
        .setChannel("89s3892b-0234-9023-d9a2-9023ad802a9s", ChannelType.IOS);

Response<String> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

named_user = UA::NamedUser.new(client: airship)
named_user.disassociate(channel_id: '89s3892b-0234-9023-d9a2-9023ad802a9s', device_type: 'ios')

This example disassociates a channel the the named user id "user-id-1234".

Lookup

curl https://go.urbanairship.com/api/named_users/?id=user-id-1234 \
   -X GET \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -u "<AppKey>:<MasterSecret>"
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
named_user = ua.NamedUser(airship, 'user-id-1234')
user = named_user.lookup()
import com.urbanairship.api.nameduser.NamedUserListingRequest;
import com.urbanairship.api.nameduser.model.NamedUserListingResponse;

NamedUserListingRequest request = NamedUserListingRequest.newRequest("user-id-1234");
Response<NamedUserListingResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

named_user = UA::NamedUser.new(client: airship)
named_user.named_user_id = 'user-id-1234'
user = named_user.lookup

This example looks up information on the single named user id "user-id-1234".

Listing

curl https://go.urbanairship.com/api/named_users \
   -X GET \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -u "<AppKey>:<MasterSecret>"
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
named_user_list = ua.NamedUserList(airship)

for user in named_user_list:
   print(user.named_user_id)
import com.urbanairship.api.nameduser.NamedUserListingRequest;
import com.urbanairship.api.nameduser.model.NamedUserListingResponse;

NamedUserListingRequest request = NamedUserListingRequest.newRequest();
Response<NamedUserListingResponse> response = client.execute(request);
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

named_user_list = UA::NamedUserList.new(client: airship)

named_user_list.each do |named_user|
   puts(named_user)
end

This example lists all named users associated with an app.

Tags

curl https://go.urbanairship.com/api/named_users/tags \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": {
             "named_user_id": "user-id-1234"
          },
          "add": {
             "crm": "business",
             "other-group": ["puppies","kittens"]
          }
       }'

# To remove tags, replace the "add" key with the "remove" key.
# To set tags, use the "set" key.
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
named_user = ua.NamedUser(airship, 'user-id-1234')
named_user.tag('crm', add=['business'])
named_user.tag('other-group', add=['puppies', 'kittens'])

# To remove tags, replace the "add" key with the "remove" key.
# To set tags, use the "set" key.
Set<String> crmTags = new HashSet<String>();
crmTags.add("business");

Set<String> otherGroupTags = new HashSet<String>();
otherGroupTags.add("puppies");
otherGroupTags.add("kittens");

NamedUserTagRequest request = NamedUserTagRequest.newRequest()
        .addNamedUsers("user-id-1234")
        .addTags("crm", crmTags)
        .addTags("other-group", otherGroupTags);

Response<String> response = client.execute(request);

// To remove tags, replace "addTags" with "removeTags".
// To set tags, use "setTags".
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

named_user_tags = UA::NamedUserTags.new(client: airship)
named_user_ids = ['user-id-1234']
named_user_tags.set_audience(user_ids: named_user_ids)
named_user_tags.add(group_name: 'crm', tags: ['business'])
named_user_tags.add(group_name: 'other-group', tags: ['puppies', 'kittens'])
named_user_tags.send_request

In this example we add tags to a named user.

A single request may contain an "add" key, a "remove" key, both an "add" and "remove" key, or a single "set" key.

Personalization

You can deliver personalized messages via Templates.

Create Template

curl https://go.urbanairship.com/api/templates \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "name": "Welcome Message",
          "description": "Our welcome message",
          "variables": [
              {
                  "key": "TITLE",
                  "name": "Title",
                  "description": "e.g. Mr, Ms, Dr, etc.",
                  "default_value": ""
              },
              {
                  "key": "FIRST_NAME",
                  "name": "First Name",
                  "description": "Given name",
                  "default_value": null
              },
              {
                  "key": "LAST_NAME",
                  "name": "Last Name",
                  "description": "Family name",
                  "default_value": null
              }
          ],
          "push": {
              "notification": {
                  "alert": "Hello {{TITLE}} {{FIRST_NAME}} {{LAST_NAME}}, this is your welcome message!"
              }
          }
      }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')

new_template = ua.Template(airship)
new_template.name = 'Welcome Message'
new_template.description = 'Our welcome message'
new_template.variables = [
     {
         'key': 'TITLE',
         'name': 'Title',
         'description': 'e.g. Mr., Ms., Dr., etc.',
         'default_value': ''
     },
     {
         'key': 'FIRST_NAME',
         'name': 'First Name',
         'description': 'Given name',
         'default_value': None
     },
     {
         'key': 'LAST_NAME',
         'name': 'Last Name',
         'description': 'Family name',
         'default_value': None
     }
]
new_template.push = {
    'notification': {
        'alert': 'Hello {{TITLE}} {{FIRST_NAME}} {{LAST_NAME}}, this is your welcome message!'
    }
}
new_template.create()
print (new_template.template_id)  # To get the template ID for future use
import com.urbanairship.api.push.model.notification.Notification;
import com.urbanairship.api.templates.TemplateRequest;
import com.urbanairship.api.templates.model.PartialPushPayload;
import com.urbanairship.api.templates.model.TemplateResponse;
import com.urbanairship.api.templates.model.TemplateVariable;

TemplateVariable titleVariable = TemplateVariable.newBuilder()
        .setKey("TITLE")
        .setName("Title")
        .setDescription("e.g. Mr, Ms, Dr, etc")
        .setDefaultValue("")
        .build();

TemplateVariable firstNameVariable = TemplateVariable.newBuilder()
        .setKey("FIRST_NAME")
        .setName("First Name")
        .setDescription("Given name")
        .setDefaultValue(null)
        .build();

TemplateVariable lastNameVariable = TemplateVariable.newBuilder()
        .setKey("LAST_NAME")
        .setName("Last Name")
        .setDescription("Family name")
        .setDefaultValue("")
        .build();

PartialPushPayload partialPushPayload = PartialPushPayload.newBuilder()
        .setNotification(Notification.newBuilder()
                .setAlert("Hello {{TITLE}} {{FIRST_NAME}} {{LAST_NAME}}, this is your welcome message!")
                .build()
        )
        .build();

TemplateRequest request = TemplateRequest.newRequest()
        .setName("Welcome Message")
        .setDescription("Our welcome message")
        .addVariable(titleVariable)
        .addVariable(firstNameVariable)
        .addVariable(lastNameVariable)
        .setPush(partialPushPayload);

Response<TemplateResponse> response = client.execute(request);
# The Templates API is not currently supported by the Ruby library.

This example creates a new template. The response will include the template_id which will be used in the next example to send the message to.

Push to Template

curl https://go.urbanairship.com/api/templates/push \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "device_types": ["android","ios"],
          "audience": {
             "named_user": "user-id-1234"
          },
          "merge_data": {
              "template_id": "<template-id-123>",
              "substitutions": {
                  "TITLE": "Ms.",
                  "FIRST_NAME": "Alice",
                  "LAST_NAME": "Jones"
              }
          }
      }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')

push = airship.create_template_push()
push.audience = ua.named_user('user-id-1234')
push.device_types = ua.device_types('android', 'ios')
push.merge_data = ua.merge_data(
    template_id='template-id-123',
    substitutions={
        'TITLE': 'Ms.',
        'FIRST_NAME': 'Alice',
        'LAST_NAME': 'Jones'
    }
)
push.send()
import com.urbanairship.api.push.model.DeviceType;
import com.urbanairship.api.push.model.DeviceTypeData;
import com.urbanairship.api.push.model.audience.Selectors;
import com.urbanairship.api.templates.TemplatePushRequest;
import com.urbanairship.api.templates.model.TemplatePushPayload;
import com.urbanairship.api.templates.model.TemplateResponse;
import com.urbanairship.api.templates.model.TemplateSelector;

TemplatePushPayload payload = TemplatePushPayload.newBuilder()
        .setAudience(Selectors.namedUser("user-id-1234"))
        .setDeviceTypes(DeviceTypeData.of(DeviceType.ANDROID, DeviceType.IOS))
        .setMergeData(TemplateSelector.newBuilder()
                .setTemplateId("template-id-123")
                .addSubstitution("TITLE", "Ms.")
                .addSubstitution("FIRST_NAME", "Alice")
                .addSubstitution("LAST_NAME", "Jones")
                .build())
        .build();

TemplatePushRequest request = TemplatePushRequest.newRequest().addTemplatePushPayload(payload);
Response<TemplateResponse> response = client.execute(request);
# The Templates API is not currently supported by the Ruby library.

This example sends a push notification to devices associated with the Named User ID user-id-1234 using the template template-id-123 created above.

Update Template

curl https://go.urbanairship.com/api/templates/<template-id-123> \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "name": "Welcome Message",
          "description": "Our welcome message",
          "push": {
              "notification": {
                  "alert": "Hello {{FIRST_NAME}} {{LAST_NAME}}, this is your welcome message!"
              }
          }
      }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')

template_id = 'template-id-123'
updated_template = ua.Template(airship)
updated_template.push = {
    'notification': {
        'alert': 'Hello {{FIRST_NAME}} {{LAST_NAME}}, this is your welcome message!'
    }
}
updated_template.update(template_id)
// Example coming soon.
# The Templates API is not currently supported by the Ruby library.

This example updates the template template-id-123 by removing the TITLE in the alert message.

Lookup Template

curl "https://go.urbanairship.com/api/templates/<template-id-123>" \
   -X GET \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json"
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')

template_id = 'template-id-123'
template = ua.Template(airship).lookup(template_id)
print (
    template.template_id, template.created_at, template.modified_at,
    template.last_used, template.name, template.description,
    template.variables, template.push
)
import com.urbanairship.api.templates.TemplateListingRequest;
import com.urbanairship.api.templates.model.TemplateListingResponse;

TemplateListingRequest request = TemplateListingRequest.newRequest("template-id-123");
Response<TemplateListingResponse> response = client.execute(request);
# The Templates API is not currently supported by the Ruby library.

This example retrieves information about the specified template template-id-123.

List Templates

curl "https://go.urbanairship.com/api/templates" \
   -X GET \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json"
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')

for template in ua.TemplateList(airship):
   template_id = template.template_id
   print (
       template.template_id, template.created_at, template.modified_at,
       template.last_used, template.name, template.description,
       template.variables, template.push
   )
import com.urbanairship.api.templates.TemplateListingRequest;
import com.urbanairship.api.templates.model.TemplateListingResponse;

TemplateListingRequest request = TemplateListingRequest.newRequest();
Response<TemplateListingResponse> response = client.execute(request);
# The Templates API is not currently supported by the Ruby library.

This example lists all templates of an application.

Delete Template

curl "https://go.urbanairship.com/api/templates/<template-id-123>" \
   -X DELETE \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json"
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')

template_id = 'template-id-123'
ua.Template(airship).delete(template_id)
import com.urbanairship.api.templates.TemplateDeleteRequest;
import com.urbanairship.api.templates.model.TemplateResponse;

TemplateDeleteRequest request = TemplateDeleteRequest.newRequest("template-id-123");
Response<TemplateResponse> response = client.execute(req);
# The Templates API is not currently supported by the Ruby library.

This example deletes the specified template template-id-123.

Channels

Channels are Urban Airship’s unique identifiers for addressing applications on iOS, Android, Amazon, and web devices.

Channel Lookup

curl "https://go.urbanairship.com/api/channels/<channel_id>" \
   -X GET \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json"
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')

channel = ua.ChannelInfo(airship).lookup('channel_id')
print (channel.channel_id, channel.device_type, channel.tags,
       channel.push_address, channel.named_user_id, channel.opt_in)
import com.urbanairship.api.channel.ChannelRequest;
import com.urbanairship.api.channel.model.ChannelResponse;
import com.urbanairship.api.channel.model.ChannelView;

ChannelRequest request = ChannelRequest.newRequest("channel_id");
Response<ChannelResponse> response = client.execute(request);
ChannelView channel = response.getBody().get().getChannelView().get();
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

channel_client = UA::ChannelInfo.new(client: airship)
channel_info = channel_client.lookup(uuid: 'channel_id')
puts(channel_info)

This example retrieves information about channel_id.

Channel Listing

curl "https://go.urbanairship.com/api/channels" \
   -X GET \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json"
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')

channel_id = None
for channel in ua.ChannelList(airship):
    channel_id = channel.channel_id
    print (channel.channel_id, channel.device_type, channel.tags,
           channel.push_address, channel.named_user_id, channel.opt_in)
import com.urbanairship.api.channel.ChannelRequest;
import com.urbanairship.api.channel.model.ChannelResponse;
import com.urbanairship.api.channel.model.ChannelView;

ChannelRequest request = ChannelRequest.newRequest();
Response<ChannelResponse> response = client.execute(request);
ChannelView channels = response.getBody().get().getChannelView().get();
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

channel_list = UA::ChannelList.new(client: airship)

channel_list.each do |channel|
    puts(channel)
end

puts(channel_list.count)

This example retrieves information about the channels registered to the application.

Uninstall Channel

curl "https://go.urbanairship.com/api/channels/uninstall" \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "channel_id": "android_channel_id",
          "device_type": "android" }
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')

channel_uninstall = ua.ChannelUninstall(airship)

channel = {"channel_id": "android_channel_id",
          "device_type": "android"}

channel_uninstall.uninstall(channel)
// The channel uninstall API is not currently supported by the Java library.
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

channel_uninstall = UA::ChannelUninstall.new(client: airship)

channel = {"channel_id" => "android_channel_id",
         "device_type" => "android"}

channel_uninstall.uninstall(channels: channel)

This example uninstalls a single channel from the android platform.

Open Channels

Open Channels are an extension of channels, supporting notification payloads to any messaging channel you choose via the Urban Airship API.

Register New / Update Channel

curl "https://go.urbanairship.com/api/channels/open" \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
         "channel" : {

            "type": "open",
            "opt_in": true,
            "address": "e3f814fd-c5aa-4599-b25e-3b7b59c80160",

            "tags": ["greenTag"],

            "timezone" : "America/Los_Angeles",
            "locale_country" : "US",
            "locale_language" : "en",

            "open": {
               "open_platform_name": "slack",
               "identifiers": {
                  "cid": 123456
               }
            }
         }
      }'
# The Open Channels API is not currently supported by the Python library.
// The Open Channels API is not currently supported by the Java library.
# The Open Channels API is not currently supported by the Ruby library.

This example creates a new open channel. The response will return a 200 status and the newly created channel.

Open Channel Lookup

curl "https://go.urbanairship.com/api/channels/<channel_id>" \
   -X GET \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json"
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')

channel = ua.ChannelInfo(airship).lookup('channel_id')
print (channel.channel_id, channel.device_type, channel.tags,
       channel.push_address, channel.named_user_id, channel.opt_in)
import com.urbanairship.api.channel.ChannelRequest;
import com.urbanairship.api.channel.model.ChannelResponse;
import com.urbanairship.api.channel.model.ChannelView;

ChannelRequest request = ChannelRequest.newRequest("channel_id");
Response<ChannelResponse> response = client.execute(request);
ChannelView channel = response.getBody().get().getChannelView().get();
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: 'app_key', secret: 'master_secret')

channel_client = UA::ChannelInfo.new(client: airship)
channel_info = channel_client.lookup(uuid: 'channel_id')
puts(channel_info)

This example retrieves information about the <channel_id>

Push to Open Channel

curl "https://go.urbanairship.com/api/push" \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "audience": {"open_channel": "e3f814fd-c5aa-4599-b25e-3b7b59c80160"},
          "notification": { "alert" : "Hooray for avocados!" },
          "device_types": ["open::avocado"]
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')

push = airship.create_push()
push.audience = ua.open_channel('e3f814fd-c5aa-4599-b25e-3b7b59c80160')
push.notification = ua.notification(alert='Hooray for avocados!')
push.device_types = ua.device_types('open::avocado')
push.send()
// The Open Channels API is not currently supported by the Java library.
# The Open Channels API is not currently supported by the Ruby library.

This example sends a push to an open channel.

Uninstall Open Channels

curl "https://go.urbanairship.com/api/channels/open/uninstall" \
   -X POST \
   -u "<AppKey>:<MasterSecret>" \
   -H "Accept: application/vnd.urbanairship+json; version=3" \
   -H "Content-Type: application/json" \
   -d '{
          "address": "e3f814fd-c5aa-4599-b25e-3b7b59c80160",
          "open_platform_name": "slack" }
       }'
# The Open Channels API is not currently supported by the Python library.
// The Open Channels API is not currently supported by the Java library.
# The Open Channels API is not currently supported by the Ruby library.

This example uninstalls a single open channel.

Never miss out on product updates

Click "Allow" in the browser prompt in the upper left hand corner of your browser.

Next, we'll allow you to choose what sort of notifications you'd like to receive.

Choose your notification topics

Product Subscription Options

    Platform Subscription Options