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. To that end, 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 and Java, two of the three languages for which we currently provide supported Server Libraries.

This document will evolve over time 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.

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

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

Push

The Push API is used to send notifications to opted in devices. The process for sending out a notification via the API can be abstracted to the following 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

Send a push message 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="Hello, world!")
push.device_types = ua.all_
push.send()
import com.urbanairship.api.client.*;
import com.urbanairship.api.client.PushResponse;
import com.urbanairship.api.client.Response;
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.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("Here's a push!"))
           .setDeviceType(DeviceTypeData.of(DeviceType.IOS))
           .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
cl = UA::Client.new(key:'app_key', secret:'master_secret')

push = cl.create_push
push.audience = UA.all
push.notification = UA.notification(alert: 'Hello, world!')
push.device_types = UA.all
push.send_push

Push to Platform

You can send a push message to a specific platform. The example below sends a message to iOS and Android 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" : "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()
// Set up a payload for the message you want to send
PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.all())
      .setNotification(Notifications.alert("Hey Android and iOS!!"))
      .setDeviceType(DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID))
      .build();

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

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

push = cl.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

Push to Device Identifiers

If you would like to target specific users, you can push to device identifiers. The example below 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": [
                {"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 = 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("Hi iOS users."))
      .setDeviceType(DeviceTypeData.of(DeviceType.IOS))
      .build();

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

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

push = cl.create_push
push.audience = UA.or( UA.ios_channel('iosChannel1')
                     , UA.ios_channel('iosChannel2')
                     , UA.ios_channel('iosChannel3')
                     )
push.notification = UA.notification(alert: 'Hi iOS users')
push.device_types = UA.device_types(['ios'])
push.send_push

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

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 = 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()
// Set up a payload for the message you want to send
PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.androidChannels("<androidChannel1>", "<androidChannel2>"))
      .setNotification(Notifications.alert("Hi Android users!"))
      .setDeviceType(DeviceTypeData.of(DeviceType.ANDROID))
      .build();

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

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

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

Push to Tag

You can send pushes to devices with certain tags. In the example below, 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": "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()
// Select the tags breakingnews and either of the tags sports or worldnews
Selector orSelector = Selectors.tags("sports", "worldnews");
Selector bnewsSelector = Selectors.tag("breakingnews");
Selector compound = Selectors.and(orSelector, bnewsSelector);

// Set up a payload for the message you want to send
PushPayload payload = PushPayload.newBuilder()
      .setAudience(compound)
      .setNotification(Notifications.alert("BREAKING: Important news is happening")
      .setDeviceTypes(DeviceTypeData.all())
      .build();

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

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

push = cl.create_push
push.audience = UA.and(
   UA.tag('breakingnews'),
   UA.or(
      UA.tag('worldnews'),
      UA.ios_channel('sports')
   )
)
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": {
             "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 = {"tag": "tag1","group": "group_name"}
push.notification = ua.notification(alert="Hello Tag Group!!")
push.device_types = ua.all_
push.send()
Selector sports = Selectors.tagWithGroup("sports", "device")
Selector gold = Selectors.tagWithGroup("gold", "loyalty")
Selector compound = Selectors.andSelector(sports, gold)

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

PushRequest push = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(push);
# Tag Groups are not currently supported by the Ruby library.

The process of pushing to a Device Property Tag is similar:

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": "Africa/Addis_Ababa", "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": "true","group": "ua_background_enabled"}
push.notification = ua.notification(alert="Hello Device Property Tag!!")
push.device_types = ua.all_
push.send()
Selector tz = Selectors.tagWithGroup("Africa/Addis_Ababa", "timezone")

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

PushRequest push = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(push);
# Device Property Tags require the use of Tag Groups, which are currently unsupported
# by the Ruby library

The only difference between pushing to a Device Property Tag and any other tag is that 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's 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's up segment?"))
      .setDeviceTypes(DeviceTypeData.all())
      .build();

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

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

push = cl.create_push
push.audience = UA.segment('segmentID')
push.notification = UA.notification(alert: "What's 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('074e84a2-9ed9-4eee-9ca4-cc597bfdbef3')
push.notification = ua.notification(
    alert="We are in your browser now!"
    web=ua.web(
        icon={
        'url': 'https://www.example.com/Sunshine_icon.png'
        },
    title='Hello Sunshine',
    extra={'article_id': '12345'},
    )
)
push.device_types = ua.device_types('web')
push.send()
// Set up a payload for the message you want to send
UrbanAirshipClient client = UrbanAirshipClient.newBuilder()
                .setKey("app_key")
                .setSecret("master_secret")
                .build();

WebIcon webIcon = WebIcon.newBuilder()
                .setUrl("https://i.ytimg.com/vi/PNgykntrIzE/maxresdefault.jpg")
                .build();

WebDevicePayload webPayload = WebDevicePayload.newBuilder()
                .setAlert("Web alert!")
                .setTitle("title")
                .addExtraEntry("article_id", "12345")
                .setWebIcon(webIcon)
                .build();

PushPayload payload = PushPayload.newBuilder()
                .setAudience(Selectors.channel("074e84a2-9ed9-4eee-9ca4-cc597bfdbef3"))
                .setNotification(Notifications.notification(webPayload))
                .setDeviceTypes(DeviceTypeData.of(DeviceType.WEB))
                .build();

PushRequest pushRequest = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(pushRequest);
#  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

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.

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" : "2015-02-16T10:30:00" },
          "push": {
             "audience": { "tag": "usa" },
             "notification": { "alert": "Guess what day it is!" },
             "device_types": "all"
          }
       }'
import urbanairship as ua
import datetime

sched = airship.create_scheduled_push()
sched.schedule = ua.schedule_time(
   datetime.datetime(2015, 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()
// Set up a payload for the message you want to send
PushPayload payload = PushPayload.newBuilder()
      .setAudience(Selectors.all())
      .setNotification(Notifications.alert("Hello, World."))
      .setDeviceTypes(DeviceTypeData.of(DeviceType.IOS))
      .build();

DateTime dt = new DateTime(2015, 16, 02, 10, 30, 0)

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

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

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

push = cl.create_push
push.audience = UA.tag('usa')
push.notification = UA.notification(alert: 'Guess what day it is!')
push.device_types = UA.all
sched = cl.create_schedule_push
sched.schedule = UA.scheduled_time(Time.new(2015, 2, 16, 10, 30))
sched.push = push
sched.send_push

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

Automation

Automated messages are handled via the pipelines API. Broadly, a request to the pipelines api must contain outcome and enabled attributes, and some sort of 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

The following request creates an automated message that sends when the tag bought-shoes is added to a device:

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 u like shoes bruh" },
                "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.

Tag Trigger and Delay

The following request is identical to the previous one, except we now add the delay attribute:

curl https://go.urbanairship.com/api/pipelihes \
   -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 u like shoes br" },
                "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.

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

First Open Trigger

This request creates an automated message with a 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.

List Enabled Pipelines

This request will display all automated messages that are currently active:

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.

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

Tags

Channel Tag Operations

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

Example (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

channel_tags = ua.devices.ChannelTags(airship)
ios_audience = ['channel1', 'channel2', 'channel3']
android_audience = 'channel4'
amazon_audience = None
channel_tags.set_audience(ios_audience, android_audience, amazon_audience)
channel_tags.add('group_name', ['tag1', 'tag2', 'tag3'])
channel_tags.send()
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:'application_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(group_name: 'crm', tags: ['partner_offers', 'new_customer'])

Example (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": {
            "loyalty": ["gold_member"]
         }
      }'
import urbanairship as ua

channel_tags = ua.devices.ChannelTags(airship)
ios_audience = ['channel1', 'channel2', 'channel3']
android_audience = 'channel4'
amazon_audience = None
channel_tags.set_audience(ios_audience, android_audience, amazon_audience)
channel_tags.remove('group_name', 'tag4')
channel_tags.send()
// The /api/channels/tags/ endpoint is not currently supported by the Java library.
require 'urbanairship'
UA = Urbanairship
airship = UA::Client.new(key:'application_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(group_name: 'loyalty', tags: ['gold_member'])

Example (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": {
            "best_tag_group": ["a_tag"]
         }
      }'
import urbanairship as ua

channel_tags = ua.devices.ChannelTags(airship)
ios_audience = ['channel1', 'channel2', 'channel3']
android_audience = 'channel4'
amazon_audience = None
channel_tags.set_audience(ios_audience, android_audience, amazon_audience)
channel_tags.set('group_name', 'tag4')
channel_tags.send()
// The /api/channels/tags/ endpoint is not currently supported by the Java library.
require 'urbanairship'
UA = Urbanairship
airship = UA::Client.new(key:'application_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(group_name: 'best_tag_group', tags: ['a_tag'])

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

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

The following request lists tags associated with a certain app key:

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.

Create Tag

The following request creates the pizza_yolo 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.

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 the warnings here for more information.

The following request removes the tag pizza_yolo from three Android devices, and adds it to two iOS devices:

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, 'tag1')
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.

Delete Tag

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

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.

Batch Modification of Tags

The batch endpoint takes an array of device identifier and tag array pairs, like this:

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

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:

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_amazon_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.

Message Center

The process for sending a rich 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 a title and body attribute. Together, these two attributes define your rich message. Additionally, there are a number of optional attributes. Please see the Message Center documentation for a 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

Send a rich push message to your entire audience:

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 rich 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.device_types = ua.device_types('ios', 'android', 'amazon')

push.message = ua.message(
   title="New follower",
   body="Justin Bieber is now following you!",
   content_type="text/html"
)

push.notification = ua.notification(alert="Guess who's following you...")
push.send()
RichPushMessage message = RichPushMessage.newBuilder()
      .setTitle("New Follower")
      .setBody("Justin Bieber is now following you!")
      .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("Guess who's following you..."))
      .setDeviceType(DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID, DeviceType.AMAZON))
      .build();

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

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

push = cl.create_push
push.audience = UA.all
push.device_types = UA.device_types(['ios', 'android', 'amazon'])
push.message = UA.message(
   title: 'New follower',
   body: 'Justin Bieber is now following you!'
)
push.send_push

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.

In this example, we include a link in the body of our rich message:

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.device_types = ua.all_
push.message = ua.message(
   title = "Check this out!",
   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.send()
RichPushMessage message = RichPushMessage.newBuilder()
      .setTitle("Check this out!")
      .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"))
      .setDeviceType(DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID, DeviceType.AMAZON))
      .build();

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

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

push = cl.create_push
push.audience = UA.all
push.device_types = UA.all
push.message = UA.message(
   title: 'Check this out!',
   body: '<html><h1>Headline</h1><p>We can <a href=\"http://urbanairship.com\">insert a link!</a></p></html>'
)
push.send_push

Broadcast With Embedded YouTube Video

This example includes an embedded YouTube video in the body:

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 rich 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/RGjGf-tBg_E\" 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.device_types = ua.all_
push.message = ua.message(
   title = "Check this out!",
   body =  "<html><h1>Headline</h1><iframe width=\"560\" height=\"315\" src=\"//www.youtube.com/embed/RGjGf-tBg_E\" frameborder=\"0\" allowfullscreen></iframe></html>"
)
push.notification = ua.notification(alert="A VIDEO in a rich message?! What will they think of next.")
push.send()
RichPushMessage message = RichPushMessage.newBuilder()
      .setTitle("Check this out!")
      .setBody("<html><h1>Headline</h1><iframe width=\"560\" height=\"315\" src=\"//www.youtube.com/embed/RGjGf-tBg_E\" 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 rich message? What will they think of next."))
      .setDeviceType(DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID, DeviceType.AMAZON))
      .build();

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

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

push = cl.create_push
push.audience = UA.all
push.device_types = UA.all
push.message = UA.message(
   title: 'Check this out!',
   body: '<html><h1>Headline</h1><iframe width=\"560\" height=\"315\" src=\"//www.youtube.com/embed/RGjGf-tBg_E\" frameborder=\"0\" allowfullscreen></iframe></html>'
)
push.send_push

Actions

Add or Remove Tags

If a user taps on this notification, it will add the tags pizza and news 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": "all",
          "notification": {
             "alert": "Mayor uses fork to eat pizza, public outraged.",
             "actions": { "add_tag" : ["pizza", "news"] }
          },
          "device_types": ["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="Mayor uses fork to eat pizza, public outraged."
   actions=ua.actions(
      add_tag="pizza",
      add_tag="news
   )
)
push.device_types = ua.all_
push.send()
// Create the tag set
Set<String> tags = new HashSet<String>();
tags.add("mayor");
tags.add("pizza");

// 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 push = PushRequest.newRequest(payload);
Response<PushResponse> response = client.execute(push);
require 'urbanairship'

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

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

To remove tags, simply use the remove_tag attribute rather than the add_tag attribute.

Share Text

The following API request will send a push containing the share action:

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": ["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.all_
push.send()
// 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.ANDROID))
      .build();

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

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

push = cl.create_push
push.audience = UA.all
push.device_types = 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.send_push

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 an app of their choice, where they will have the option to share the text “BestApp9000 is the best app ever.”

Open an External URL

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

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": ["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="Read some news or something",
   actions=ua.actions(
      open_={
         "type": "url",
         "content": "http://www.theatlantic.com"
      }
   )
)
push.device_types = ua.all_
push.send()
// 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.ANDROID,DeviceType.IOS))
      .build();

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

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

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

Interactive Notifications

Follow and Unfollow

You can also 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:

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-2015"
                       }
                   }
               }
           },
           "device_types": "all"
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.all_
push.device_types = 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-2015")
      }
   )
)

push.send()
Interactive interactive = Interactive.newBuilder()
      .setType("ua_follow")
      .setButtonActions(
         ImmutableMap.of(
            "follow",
            Actions.newBuilder()
               .addTags(new AddTagAction(TagActionData.single("pdx-snowstorm-2015"))))
      .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.all())
         .build();

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

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

push = cl.create_push
push.audience = UA.all
push.device_types = 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: { add_tag: 'pdx-snowstorm-2015' }
      }
   )
)
push.send_push

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

Now, any follow-up notifications on this story should be pushed to the tag pdx-snowstorm-2015. 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-2015 tag is removed from 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-2015" },
          "notification": {
             "alert": "Minor snow storm reduces Portland to post-apocalyptic wasteland.",
             "interactive": {
                "type": "ua_unfollow",
                "button_actions": {
                   "unfollow": {
                      "remove_tag": "pdx-snowstorm-2015"
                   }
                }
             }
          },
          "device_types": "all"
       }'
import urbanairship as ua

airship = ua.Airship('app_key', 'master_secret')
push = airship.create_push()
push.audience = ua.tag("pdx-snowstorm-2015")
push.device_types = ua.device_types('ios', 'android')

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-2015")
      }
   )
)

push.send()
Interactive interactive = Interactive.newBuilder()
      .setType("ua_unfollow")
      .setButtonActions(
         ImmutableMap.of(
            "unfollow",
            Actions.newBuilder()
               .removeTags(new AddTagAction(TagActionData.single("pdx-snowstorm-2015"))))
      .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-2015"))
         .setNotification(interactiveNotification)
         .setDeviceTypes(DeviceTypeData.all())
         .build();
require 'urbanairship'

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

push = cl.create_push
push.audience = UA.tag('pdx-snowstorm-2015')
push.device_types = UA.all
push.notification = UA.notification(
   alert: 'Minor snow storm reduces Portland to post-apocalyptic wasteland.',
   interactive: UA.interactive(
      type: 'ua_unfollow',
      button_actions: {
         follow: { remove_tag: 'pdx-snowstorm-2015' }
      }
   )
)
push.send_push

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.

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.

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.

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.

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:

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" : "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.

Reports

Response Listing

This request will list all pushes, plus associated basic information, in the given timeframe:

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

airship = ua.Airship(app_key, master_secret)

start_date = datetime(2015, 6, 29)
end_date = datetime(2015, 6, 30)
return_list = ua.reports.ResponseList(airship, start_date, end_date)
push_responses = [response for response in return_list]
DateTime start = new DateTime(2014, 10, 1, 12, 0, 0, 0);
DateTime end = start.plus(Period.hours(48));

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

Response<PushListingResponse> response = client.execute(request);
require 'urbanairship'
UA = Urbanairship
airship = UA::Client.new(key: 'application_key', secret: 'master_secret')
response_list = UA::ResponseList.new(
   client: airship,
   start_date: '2014-05-05',
   end_date: '2015-05-015',
   limit: 20,
   push_id_start: 'start_id'
)
response_list.each do |resp|
   puts(resp)
end

App Opens Report

This request retrieves the App Opens for the first two weeks of December 2014, with an hourly precision:

curl "https://go.urbanairship.com/api/reports/opens/?start=2014-12-1%2010:00&end=2014-12-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(2015, 6, 1)
end_date = datetime(2015, 7, 1)
precision = 'HOURLY'
listing = ua.reports.AppOpensList(airship, start_date, end_date, precision)

for resp in listing:
  print(resp.date, resp.android, resp.ios)
DateTime start = new DateTime(2014, 12, 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<PlatformStatsRequest> response = client.execute(request);
require 'urbanairship'
UA = Urbanairship
airship = UA::Client.new(key:'application_key', secret:'master_secret')
listing = UA::AppOpensList.new(
    client: airship,
    start_date: '2014-12-01',
    end_date: '2015-12-14',
    precision: 'HOURLY'
)
listing.each do |app_opens|
    puts(app_opens)
end

Time in App Report

This request retrieves the Time In App for the first two weeks of December 2014, with a daily precision:

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

airship = ua.Airship(app_key, master_secret)

start_date = datetime(2016, 8, 1)
end_date = datetime(2016, 9, 1)
precision = 'DAILY'
listing = ua.reports.TimeInAppList(airship, start_date, end_date, precision)

for resp in listing:
  print(resp.date, resp.android, resp.ios)
DateTime start = new DateTime(2014, 12, 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.HOURLY);

Response<PlatformStatsRequest> response = client.execute(request);
require 'urbanairship'
UA = Urbanairship
airship = UA::Client.new(key:'application_key', secret:'master_secret')
listing = UA::TimeInAppList.new(
    client: airship,
    start_date: '2015-06-01',
    end_date: '2015-08-01',
    precision: 'HOURLY'
)
listing.each do |time_in_app|
    puts(time_in_app)
end

Statistics

The following request will retrieve push statistics for the first 12 hours of December 1, 2014:

curl "https://go.urbanairship.com/api/push/stats/?start=2014-12-01&end=2014-12-01+12:00" \
   -u "<AppKey>:<MasterSecret>"
# The Reports API is not currently supported by the Python library.
DateTime start = new DateTime(2014, 12, 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.

Segments

Retrieve Segment List

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

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)
SegmentListingRequest request = SegmentListingRequest.newRequest();
require 'urbanairship'
UA = Urbanairship
airship = UA::Client.new(key: 'application_key', secret: 'master_secret')
segment_list = UA::SegmentList.new(client: airship)

segment_list.each do |segment|
   puts(segment['display_name'])
end

Get Segment Info

This request will give the information associated with a given <SegmentID>:

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")
SegmentLookupRequest request = SegmentLookupRequest.newRequest("segmentId");
require 'urbanairship'
UA = Urbanairship
airship = UA::Client.new(key: 'application_key', secret: 'master_secret')
segment = UA::Segment.new(client: airship)
segment.from_id(id: 'segment_id')

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

Create a Segment

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

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")
)
Selector andSelector = Selectors.tags("blue", "green")
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: 'application_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

Create a Location-Based Segment

The following request creates a segment that consists of devices that:

  • Have been in San Francisco at some point over the past 3 months

  • Have the tag dancer

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" }
                }
             ]
          }
       }'
# The Location API is not currently supported by the Python Library
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<PlatformStatsRequest> response = client.execute(request);
# The location API is not currently supported by the Ruby library.

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. The following example pushes to devices on an uploaded weekly circular list with the tag "pizza":

Example (Uploaded):

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)
# The Java Library does not currently support targeting static lists.
# The Static List API is not currently supported by the Ruby library.

Segments can also contain Lifecycle Lists. In this case, the static_list key should have one of our Lifecycle Lists as a value. The following example pushes to all devices that:

  • Have the tag "pizza"

  • Have opened the app in the past 7 days

Example (Lifecycle):

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)
# The Java Library does not currently support targeting static lists.
# The Static List API is not currently supported by the Ruby library.

Delete a Segment

This request will delete the segment associated with the given <SegmentID>:

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)
SegmentDeleteRequest request = SegmentDeleteRequest.newRequest("segmentId");
Response<String> response = client.execute(request);
require 'urbanairship'
UA = Urbanairship
airship = UA::Client.new(key: 'application_key', secret: 'master_secret')
segment = UA::Segment.new(client: airship)
segment.from_id(id: 'segment_id')
segment.delete

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('name', 'type')
LocationRequest request = LocationRequest.newRequest("Chicago")
    .setType("city");
Response<LocationResponse> response = client.execute(request);
# The Location API is not currently supported by the Ruby library.

By latitude and longitude (note that the numbers are in the order latitude, longitude):

curl https://go.urbanairship.com/api/location/45.52,-122681944?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('lat', 'long', 'type')
Point point = Point.newBuilder()
    .setLatitude(41.8781)
    .setLongitude(87.6298)
    .build();

LocationRequest request = LocationRequest.newRequest(point)
    .setType("city");
Response<LocationResponse> response = client.execute(request);
# The Location API is not currently supported by the Ruby library.

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('lat1', 'long1', 'lat2', 'long2', 'type')
Point cornerOne = Point.newBuilder()
    .setLatitude(41.8781)
    .setLongitude(87.6298)
    .build();

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

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

LocationRequest request = LocationRequest.newRequest(box)
    .setType("province");
Response<LocationResponse> response = client.execute(request);
# The Location API is not currently supported by the Ruby library.

Named Users

Association

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

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')
NamedUserRequest request = NamedUserRequest.newAssociateRequest()
        .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:'application_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')

Disassociation

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

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')
NamedUserRequest request = NamedUserRequest.newDisassociateRequest()
        .setChannel("89s3892b-0234-9023-d9a2-9023ad802a9s", ChannelType.IOS)

Response<String> response = client.execute(request);
require 'urbanairship'
UA = Urbanairship
airship = UA::Client.new(key:'application_key', secret:'master_secret')
named_user = UA::NamedUser.new(client: airship)
named_user.disassociate(channel_id: '89s3892b-0234-9023-d9a2-9023ad802a9s', device_type: 'ios')

Lookup

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

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()
NamedUserListingRequest request = NamedUserListingRequest.newRequest("user-id-1234");
Response<NamedUserListingResponse> response = client.execute(request);
require 'urbanairship'
UA = Urbanairship
airship = UA::Client.new(key:'application_key', secret:'master_secret')
named_user = UA::NamedUser.new(client: airship)
named_user.named_user_id = 'user-id-1234'
user = named_user.lookup

Listing

The following example lists all named users associated with an app:

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)
NamedUserListingRequest request = NamedUserListingRequest.newRequest();
Response<NamedUserListingResponse> response = client.execute(request);
require 'urbanairship'
UA = Urbanairship
airship = UA::Client.new(key:'application_key', secret:'master_secret')
named_user_list = UA::NamedUserList.new(client: airship)

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

Tags

In the example below, we add tags to a named user:

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"]
          }
       }'
import urbanairship as ua
airship = ua.Airship('app_key', 'master_secret')
named_user = ua.NamedUser(airship, 'named_user_id')

named_user.tag('crm', add=['business'])
named_user.tag('other-group', add=['puppies', 'kittens'])
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);
require 'urbanairship'
UA = Urbanairship
airship = UA::Client.new(key:'application_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'])

To remove tags, replace the "add" key with the "remove" key. To set tags, use the "set" key. A single request may contain an "add" key, a "remove" key, both an "add" and "remove" key, or a single "set" key.