OneSignal Help & Documentation

Welcome to the OneSignal New IA developer hub. You'll find comprehensive guides and documentation to help you start working with OneSignal New IA as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    Support

Create notification

Sends notifications to your users

 
post https://onesignal.com/api/v1/notifications
 

The Create Notification method is used when you want your server to programmatically send notifications to a segment or individual users. You may target users in one of three ways using this method: by Segment, by Filter, or by Device. At least one targeting parameter must be specified.

You may only use one method of targeting users

If a targeting parameter of one type is used, then targeting parameters from other types may not be used. For instance, you cannot use the included_segments parameter (from segments) with the filters.

Send to Segments

Segments are the most common way developers send notifications via OneSignal. Sending to segments is easy: you simply specify which segments you want to send to, and, optionally, which ones you don't.

Parameter
Type
Description

included_segments

array_string

Required The segment names you want to target. Users in these segments will receive a notification. This targeting parameter is only compatible with excluded_segments.


Example: ["Active Users", "Inactive Users"]

excluded_segments

array_string

Segment that will be excluded when sending. Users in these segments will not receive a notification, even if they were included in included_segments. This targeting parameter is only compatible with included_segments.


Example: ["Active Users", "Inactive Users"]

Requires Authentication Key

Requires your OneSignal App Auth Key, available in Keys & IDs.

Segments Usage

  • Tip: If you want to send to all your users, just send to the All Users segment, which is available in every app you create in OneSignal.

See below for example code

Send to Users Based on Filters

Filters are a powerful way to target users, allowing you to use both data that OneSignal has about a user and any Tags your app may send OneSignal. Filters can be combined together to form advanced, highly precise user targeting. OneSignal customers use all sorts of filters to send notifications, including language, location, user activity, and more.

The filters parameter targets notification recipients using an array of JSON objects containing field conditions to check. The following are filter field options:

Option
Description

last_session

relation = ">" or "<"
hours_ago = number of hours before or after the users last session. Example: "1.1"

first_session

relation = ">" or "<"
hours_ago = number of hours before or after the users first session. Example: "1.1"

session_count

relation = ">", "<", "=" or "!="
value = number sessions. Example: "1"

session_time

relation = ">" or "<"
value = Time in seconds the user has been in your app. Example: "3600"

amount_spent

relation = ">", "<", or "="
value = Amount in USD a user has spent on IAP (In App Purchases). Example: "0.99"

bought_sku

relation = ">", "<" or "="
key = SKU purchased in your app as an IAP (In App Purchases). Example: "com.domain.100coinpack"
value = value of SKU to compare to. Example: "0.99"

tag

relation = ">", "<", "=", "!=", "exists" or "not_exists"
key = Tag key to compare.
value = Tag value to compare. Not required for "exists" or "not_exists". Example: See Formatting Filters

language

relation = "=" or "!="
value = 2 character language code. Example: "en". For a list of all language codes go here

app_version

relation = ">", "<", "=" or "!="
value = app version. Example: "1.0.0"

location

radius = in meters
lat = latitude
long = longitude

email

value = email address

Requires Authentication Key

Requires your OneSignal App Auth Key, available in Keys & IDs.

Filter Usage

  • Filter entries use AND by default; insert {"operator": "OR"} between entries to OR the parameters together.
  • For performance reasons, a maximum of 200 entries can be used at a time. The 200 entries limit includes the "field" entry and "OR" entries -- each would count towards the 200 limit.
    Below, "Formatting Example 1" would be 2 entries and "Formatting Example 2" would be 3 entries.
  • This filter targeting parameter cannot be combined with any other targeting parameters.

Formatting Filters

The power of filters comes from combining several fields and operators to precisely target your users. The following are examples of filters and how to format them:

  1. A user is level 10 and purchased an item

  2. A user is level 10 or 20

  3. A user is not VIP or is admin

  4. User's tags include key username and the user is not banned.

[
  {"field": "tag", "key": "level", "relation": ">", "value": "10"},
  {"field": "amount_spent", "relation": ">","value": "0"}
]
[
  {"field": "tag", "key": "level", "relation": "=", "value": "10"}, 
  {"operator": "OR"}, {"field": "tag", "key": "level", "relation": "=", "value": "20"}
]
[
  {"field": "tag", "key": "is_vip", "relation": "!=", "value": "true"},
  {"operator": "OR"}, {"field": "tag","key": "is_admin", "relation": "=", "value": "true"}
]
[
  {"field": "tag", "key": "username", "relation": "exists"},
  {"field": "tag", "key": "banned", "relation": "!=", "value": "true"}
]

See below for example code

Note: ANDs have priority over ORs.

Send to Specific Devices

Finally, you may also target specific devices with the create notification method. Targeting devices is typically used in two ways:

  1. For notifications that target individual users, such as if they've received a message from someone.

  2. For apps that wish to manage their own segments, such as tracking a user's followers and sending notifications to them when that user posts.

When targeting specific devices, you may use any of the following parameters together:

Parameter
Type
Description

include_player_ids

array_string

Recommended - Specific players to send your notification to. Does not require API Auth Key.

Do not combine with other targeting parameters. Not compatible with any other targeting parameters. Example: ["1dd608f2-c6a1-11e3-851d-000c2940e62c"]
Limit of 2,000 entries per REST API call

include_ios_tokens

array_string

Not Recommended - Please consider using include_player_ids instead.

Target using iOS device tokens. Warning: Only works with Production tokens.

All non-alphanumeric characters must be removed from each token. If a token does not correspond to an existing user, a new user will be created. Example: ce777617da7f548fe7a9ab6febb56cf39fba6d38203...


Limit of 2,000 entries per REST API call

include_wp_urls

array_string

Not Recommended Please consider using include_player_ids instead.

Target using Windows Phone 8.0 URIs. If a token does not correspond to an existing user, a new user will be created. Example: http://s.notify.live.net/u/1/bn1/HmQAAACPaLDr-...


Limit of 2,000 entries per REST API call

include_wp_wns_uris

array_string

Not Recommended Please consider using include_player_ids instead.

Target using Windows Phone 8.1 URIs. If a token does not correspond to an existing user, a new user will be created. Example: http://s.notify.live.net/u/1/bn1/HmQAAACPaLDr-...


Limit of 2,000 entries per REST API call

include_amazon_reg_ids

array_string

Not Recommended Please consider using include_player_ids instead.

Target using Amazon ADM registration IDs. If a token does not correspond to an existing user, a new user will be created. Example: amzn1.adm-registration.v1.XpvSSUk0Rc3hTVVV...


Limit of 2,000 entries per REST API call

include_chrome_reg_ids

array_string

Not Recommended Please consider using include_player_ids instead.

Target using Chrome App registration IDs. If a token does not correspond to an existing user, a new user will be created. Example: APA91bEeiUeSukAAUdnw3O2RB45FWlSpgJ7Ji_...


Limit of 2,000 entries per REST API call

include_chrome_web_reg_ids

array_string

Not Recommended Please consider using include_player_ids instead, as web push registration IDs can vary over time where OneSignal player IDs remain constant.

Target using Chrome Web Push registration IDs. If a token does not correspond to an existing user, a new user will be created. Example: APA91bEeiUeSukAAUdnw3O2RB45FWlSpgJ7Ji_...


Limit of 2,000 entries per REST API call

include_android_reg_ids

array_string

Not Recommended Please consider using include_player_ids instead, as android tokens occasionally change, which causes devices to become invalid and limits your audience.

Target using Android device registration IDs. If a token does not correspond to an existing user, a new user will be created. Example: APA91bEeiUeSukAAUdnw3O2RB45FWlSpgJ7Ji_...


Limit of 2,000 entries per REST API call

Specific Devices Usage

Requires Authentication Key

This method requires an application 'REST API Key' when using include_segments or filters, which is available in Keys & IDs.

NEVER use your 'REST API key' in client code, it is intended for use on your system or server only. Add the REST API Key to the HTTP 'Authorization' header as basic authentication. Check out the examples above (except the JSON example) for some tips.

See below for example code

Common Parameters

The following are parameters in Create Notifications common to all methods of targeting users.

App

Parameter
Type
Platform

app_id

string

All

Required Your OneSignal application ID, which can be found in Keys & IDs. It is a UUID and looks similar to 8250eaf6-1a58-489e-b136-7c74a864b434.

app_ids

array of strings

Android, iOS

Required Your User Auth Key, which can be found in Account.

app_ids contains an array of OneSignal app IDs. All users within these apps will receive at most one notification.

Example: ["2dd608f2-a6a1-11e3-251d-400c2940e62b", "2dd608f2-a6a1-11e3-251d-500f2950e61c"]


Important Node: No targeting parameters may be used when using the app_ids parameter. All subscribed users will receive the notification

Content & Language

The content you want to send in notifications. Read more: supported languages.

Parameter
Type
Platform
Description

contents

object

All

Required unless content_available=true or template_id is set.


The notification's content (excluding the title), a map of language codes to text for each language.


Each hash must have a language code string for a key, mapped to the localized text you would like users to receive for that language.
This field supports inline substitutions.
English must be included in the hash.


Example: {"en": "English Message", "es": "Spanish Message"}

headings

object

All

The notification's title, a map of language codes to text for each language. Each hash must have a language code string for a key, mapped to the localized text you would like users to receive for that language. A default title may be displayed if a title is not provided.
This field supports inline substitutions.


Example: {"en": "English Title", "es": "Spanish Title"}

subtitle

object

iOS 10+

The notification's subtitle, a map of language codes to text for each language. Each hash must have a language code string for a key, mapped to the localized text you would like users to receive for that language. A default title may be displayed if a title is not provided.
This field supports inline substitutions.


Example: {"en": "English Subtitle", "es": "Spanish Subtitle"}

template_id

string

All

Use a template you setup on our dashboard. You can override the template values by sending other parameters with the request. The template_id is the UUID found in the URL when viewing a template on our dashboard.


Example: be4a8044-bbd6-11e4-a581-000c2940e62c

content_available

boolean

iOS

Sending true wakes your app from background to run custom native code (Apple interprets this as content-available=1). Note: Not applicable if the app is in the "force-quit" state (i.e app was swiped away). Omit the contents field to prevent displaying a visible notification.

mutable_content

boolean

iOS 10+

Sending true allows you to change the notification content in your app before it is displayed. Triggers didReceive(_:withContentHandler:) on your UNNotificationServiceExtension.

Attachments

These are additional content attached to notifications, primarily images.

Parameter
Type
Platform
Description

data

object

All

A custom map of data that is passed back to your app.


Example: {"abc": "123", "foo": "bar"}

url

string

All

The URL to open in the browser when a user clicks on the notification.

Example: http://www.google.com


Note: iOS needs https or updated NSAppTransportSecurity in plist


This field supports inline substitutions.

ios_attachments

object

iOS 10+

Adds media attachments to notifications. Set as JSON object, key as a media id of your choice and the value as a valid local filename or URL. User must press and hold on the notification to view.


Do not set mutable_content to download attachments. The OneSignal SDK does this automatically


Example: {"id1": "https://domain.com/image.jpg"}

big_picture

string

Android

Picture to display in the expanded view. Can be a drawable resource name or a URL.

adm_big_picture

string

Amazon

Picture to display in the expanded view. Can be a drawable resource name or a URL.

chrome_big_picture

string

ChromeApp

Large picture to display below the notification text. Must be a local URL.

Action Buttons

These add buttons to notifications, allowing the user to take more than one action on a notification. Learn more about Action Buttons.

Parameter
Type
Platform
Description

buttons

array_object

iOS 8.0+, Android 4.1+ (and derivatives like Amazon)

Buttons to add to the notification. Icon only works for Android.


Example: [{"id": "id1", "text": "button1", "icon": "ic_menu_share"}, {"id": "id2", "text": "button2", "icon": "ic_menu_send"}]

Swift Example: [["id": "id1", "text": "button1"], ["id": "id2", "text": "button2"]]

web_buttons

array_object

Chrome 48+

Add action buttons to the notification. The id field is required.

Example: [{"id": "like-button", "text": "Like", "icon": "http://i.imgur.com/N8SN8ZS.png", "url": "https://yoursite.com"}, {"id": "read-more-button", "text": "Read more", "icon": "http://i.imgur.com/MIxJp1L.png", "url": "https://yoursite.com"}]

ios_category

string

iOS

Category APS payload, use with registerUserNotificationSettings:categories in your Objective-C / Swift code.

Example: calendar category which contains actions like accept and decline

iOS 10+ This will trigger your UNNotificationContentExtension whose ID matches this category.

Appearance

These parameters let you adjust notification icons, sounds, badges, and other appearance changes to your notifications.

Icons - Different platforms handle icons differently.

  • Android - Our SDK shows a bell icon by default. See our Android Notification Icons guide to change this.
  • iOS - The icon will always be your app icon. Apple does not allow this to be configured.

Sounds - By default, the device notification sound plays when a new notification arrives. You may alter this by specifying a different sound asset.

Badges - shows the number of notifications outstanding. Note: Android badges are automatically handled by OneSignal.

Parameter
Type
Platform
Description

android_background_layout

object

Android

Allowing setting a background image for the notification. This is a JSON object containing the following keys. See our Background Image documentation for image sizes.

image - Asset file, android resource name, or URL to remote image.

headings_color - Title text color ARGB Hex format. Example(Blue): "FF0000FF".

contents_color - Body text color ARGB Hex format. Example(Red): "FFFF0000"

Example: {"image": "https://domain.com/background_image.jpg", "headings_color": "FFFF0000", "contents_color": "FF00FF00"}

small_icon

string

Android

If not set a bell icon will be used or ic_stat_onesignal_default if you have set this resource name.
See: How to create small icons

large_icon

string

Android

If blank the small_icon is used. Can be a drawable resource name or a URL.
See: How to create large icons

adm_small_icon

string

Amazon

If not set a bell icon will be used or ic_stat_onesignal_default if you have set this resource name.
See: How to create small icons

adm_large_icon

string

Amazon

If blank the small_icon is used. Can be a drawable resource name or a URL.
See: How to create large icons

chrome_web_icon

string

Chrome

Sets the web push notification's icon. An image URL linking to a valid image. Common image types are supported; GIF will not animate. We recommend 256x256 (at least 80x80) to display well on high DPI devices. Firefox will also use this icon, unless you specify firefox_icon.

chrome_web_image

string

Chrome 56+ Only

Sets the web push notification's large image to be shown below the notification's title and text. Please see Web Push Notification Icons.

firefox_icon

string

Firefox

Not recommended Few people need to set Firefox-specific icons. We recommend setting chrome_web_icon instead, which Firefox will also use.

Sets the web push notification's icon for Firefox. An image URL linking to a valid image. Common image types are supported; GIF will not animate. We recommend 256x256 (at least 80x80) to display well on high DPI devices.

chrome_icon

string

ChromeApp

This flag is not used for web push For web push, please see chrome_web_icon instead.


The local URL to an icon to use. If blank, the app icon will be used.

ios_sound

string

iOS

Sound file that is included in your app to play instead of the default device notification sound. Pass "nil" to disable vibration and sound for the notification.


Example: "notification.wav"

android_sound

string

Android

Sound file that is included in your app to play instead of the default device notification sound. NOTE: Leave off file extension for Android.

Example: "notification"

adm_sound

string

Amazon

Sound file that is included in your app to play instead of the default device notification sound.

NOTE: Leave off file extension for Android.


Example: "notification"

wp_sound

string

Windows 8.0

Sound file that is included in your app to play instead of the default device notification sound.

Example: "notification.wav"

wp_wns_sound

string

Windows 8.1

Sound file that is included in your app to play instead of the default device notification sound.

Example: "notification.wav"

android_led_color

string

Android

Sets the devices LED notification light if the device has one. ARGB Hex format.

Example(Blue): "FF0000FF"

android_accent_color

string

Android

Sets the background color of the notification circle to the left of the notification text. Only applies to apps targeting Android API level 21+ on Android 5.0+ devices.

Example(Red): "FFFF0000"

android_visibility

int

Android 5.0+

Sets the lock screen visibility for apps targeting Android API level 21+ running on Android 5.0+ devices.


1 = Public (default) (Shows the full message on the lock screen unless the user has disabled all notifications from showing on the lock screen. Please consider the user and mark private if the contents are.)


0 = Private (Hides message contents on lock screen if the user set "Hide sensitive notification content" in the system settings)


-1 = Secret (Notification does not show on the lock screen at all)

ios_badgeType

string

iOS

Describes whether to set or increase/decrease your app's iOS badge count by the ios_badgeCount specified count. Can specify None, SetTo, or Increase.

None leaves the count unaffected.

SetTo directly sets the badge count to the number specified in ios_badgeCount.

Increase adds the number specified in ios_badgeCount to the total. Use a negative number to decrease the badge count.

ios_badgeCount

integer

iOS

Used with ios_badgeType, describes the value to set or amount to increase/decrease your app's iOS badge count by.

You can use a negative number to decrease the badge count when used with an ios_badgeType of Increase.

collapse_id

string

iOS 10+ Android

Only one notification with the same id will be shown on the device. Use the same id to update an existing notification instead of showing a new one.

Delivery

Parameter
Type
Platform
Description

send_after

string

All

Schedule notification for future delivery.

Examples: All examples are the exact same date & time.


"Thu Sep 24 2015 14:00:00 GMT-0700 (PDT)"


"September 24th 2015, 2:00:00 pm UTC-07:00"


"2015-09-24 14:00:00 GMT-0700"


"Sept 24 2015 14:00:00 GMT-0700"


"Thu Sep 24 2015 14:00:00 GMT-0700 (Pacific Daylight Time)"

delayed_option

string

All

Possible values are:


timezone (Deliver at a specific time-of-day in each users own timezone)


last-active Same as Intelligent Delivery. (Deliver at the same time of day as each user last used your app).


If send_after is used, this takes effect after the send_after time has elapsed.

delivery_time_of_day

string

All

Use with delayed_option=timezone.


Example: "9:00AM"

ttl

integer

iOS, Android, Chrome, ChromeWeb

Time To Live - In seconds. The notification will be expired if the device does not come back online within this time. The default is 259,200 seconds (3 days).

priority

integer

Android, Chrome, ChromeWeb

Delivery priority through the push server (example GCM/FCM). Pass 10 for high priority. Defaults to normal priority for Android and high for iOS. For Android 6.0+ devices setting priority to high will wake the device out of doze mode.

Grouping & Collapsing

Grouping lets you combine multiple notifications into a single notification to improve the user experience. Collapsing lets you dismiss old notifications in favor of newer ones.

Parameter
Type
Platform
Description

android_group

string

Android

All notifications with the same group will be stacked together using Android's Notification Stacking feature.

android_group_message

object

Android

Summary message to display when 2+ notifications are stacked together. Default is "# new messages". Include $[notif_count] in your message and it will be replaced with the current number.


Languages - The value of each key is the message that will be sent to users for that language. "en" (English) is required. The key of each hash is either a a 2 character language code or one of zh-Hans/zh-Hant for Simplified or Traditional Chinese. Read more: supported languages.


Example: {"en": "You have $[notif_count] new messages"}

adm_group

string

Amazon

All notifications with the same group will be stacked together using Android's Notification Stacking feature.

adm_group_message

object

Amazon

Summary message to display when 2+ notifications are stacked together. Default is "# new messages". Include $[notif_count] in your message and it will be replaced with the current number. "en" (English) is required. The key of each hash is either a a 2 character language code or one of zh-Hans/zh-Hant for Simplified or Traditional Chinese. The value of each key is the message that will be sent to users for that language.


Example: {"en": "You have $[notif_count] new messages"}

Platform to Deliver To

By default, OneSignal will send to every platform (each of these is true).

To only send to specific platforms, you may pass in true on one or more of these parameters corresponding to the platform you wish to send to. If you do so, all other platforms will be set to false and will not be delivered to.

Parameter
Type
Platform
Description

isIos

boolean

iOS

Indicates whether to send to all devices registered under your app's Apple iOS platform.

isAndroid

boolean

Android

Indicates whether to send to all devices registered under your app's Google Android platform.

isAnyWeb

boolean

Web

Indicates whether to send to all subscribed web browser users, including Chrome, Firefox, and Safari.

You may use this instead as a combined flag instead of separately enabling isChromeWeb, isFirefox, and isSafari, though the three options are equivalent to this one.

isChromeWeb

boolean

Web

Indicates whether to send to all Google Chrome, Chrome on Android, and Mozilla Firefox users registered under your Chrome & Firefox web push platform.

isFirefox

boolean

Web

Indicates whether to send to all Mozilla Firefox desktop users registered under your Firefox web push platform.

isSafari

boolean

Web

Does not support iOS Safari Indicates whether to send to all Apple's Safari desktop users registered under your Safari web push platform. Read more: iOS Safari

isWP

boolean

Windows Phone 8.0

Indicates whether to send to all devices registered under your app's Windows Phone 8.0 platform.

isWP_WNS

boolean

Windows Phone 8.1

Indicates whether to send to all devices registered under your app's Windows Phone 8.1+ platform.

isAdm

boolean

Amazon

Indicates whether to send to all devices registered under your app's Amazon Fire platform.

isChrome

boolean

ChromeApp

This flag is not used for web push Please see isChromeWeb for sending to web push users. This flag only applies to Google Chrome Apps & Extensions.


Indicates whether to send to all devices registered under your app's Google Chrome Apps & Extension platform.

Example Code - Create notification

Send to all subscribers - Create notification

curl --include \
     --request POST \
     --header "Content-Type: application/json; charset=utf-8" \
     --header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
     --data-binary "{\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\",
\"contents\": {\"en\": \"English Message\"},
\"included_segments\": [\"All\"]}" \
     https://onesignal.com/api/v1/notifications
{
  "app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
  "included_segments": ["All"],
  "data": {"foo": "bar"},
  "contents": {"en": "English Message"}
}
<?PHP
	function sendMessage(){
		$content = array(
			"en" => 'English Message'
			);
		
		$fields = array(
			'app_id' => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
			'included_segments' => array('All'),
      'data' => array("foo" => "bar"),
			'contents' => $content
		);
		
		$fields = json_encode($fields);
    print("\nJSON sent:\n");
    print($fields);
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
												   'Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj'));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

		$response = curl_exec($ch);
		curl_close($ch);
		
		return $response;
	}
	
	$response = sendMessage();
	$return["allresponses"] = $response;
	$return = json_encode( $return);
	
  print("\n\nJSON received:\n");
	print($return);
  print("\n");
?>
using System.IO;
using System.Net;
using System.Text;

var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;

request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");

byte[] byteArray = Encoding.UTF8.GetBytes("{"
                                        + "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
                                        + "\"contents\": {\"en\": \"English Message\"},"
                                        + "\"included_segments\": [\"All\"]}");

string responseContent = null;

try {
    using (var writer = request.GetRequestStream()) {
        writer.Write(byteArray, 0, byteArray.Length);
    }

    using (var response = request.GetResponse() as HttpWebResponse) {
        using (var reader = new StreamReader(response.GetResponseStream())) {
            responseContent = reader.ReadToEnd();
        }
    }
}
catch (WebException ex) {
    System.Diagnostics.Debug.WriteLine(ex.Message);
    System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}

System.Diagnostics.Debug.WriteLine(responseContent);
using System.IO;
using System.Net;
using System.Text;

var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;

request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");

var serializer = new JavaScriptSerializer();
var obj = new { app_id = "5eb5a37e-b458-11e3-ac11-000c2940e62c",
               contents = new { en = "English Message" },
               included_segments = new string[] {"All"} };
var param = serializer.Serialize(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);

string responseContent = null;

try {
    using (var writer = request.GetRequestStream()) {
        writer.Write(byteArray, 0, byteArray.Length);
    }

    using (var response = request.GetResponse() as HttpWebResponse) {
        using (var reader = new StreamReader(response.GetResponseStream())) {
            responseContent = reader.ReadToEnd();
        }
    }
}
catch (WebException ex) {
    System.Diagnostics.Debug.WriteLine(ex.Message);
    System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}

System.Diagnostics.Debug.WriteLine(responseContent);
params = {"app_id" => "5eb5a37e-b458-11e3-ac11-000c2940e62c", 
          "contents" => {"en" => "English Message"},
          "included_segments" => ["All"]}
uri = URI.parse('https://onesignal.com/api/v1/notifications')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.path,
                              'Content-Type'  => 'application/json;charset=utf-8',
                              'Authorization' => "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj")
request.body = params.as_json.to_json
response = http.request(request) 
puts response.body
import requests
import json

header = {"Content-Type": "application/json; charset=utf-8",
          "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"}

payload = {"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
           "included_segments": ["All"],
           "contents": {"en": "English Message"}}
 
req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload))
 
print(req.status_code, req.reason)
var sendNotification = function(data) {
  var headers = {
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
  };
  
  var options = {
    host: "onesignal.com",
    port: 443,
    path: "/api/v1/notifications",
    method: "POST",
    headers: headers
  };
  
  var https = require('https');
  var req = https.request(options, function(res) {  
    res.on('data', function(data) {
      console.log("Response:");
      console.log(JSON.parse(data));
    });
  });
  
  req.on('error', function(e) {
    console.log("ERROR:");
    console.log(e);
  });
  
  req.write(JSON.stringify(data));
  req.end();
};

var message = { 
  app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
  contents: {"en": "English Message"},
  included_segments: ["All"]
};

sendNotification(message);
#!/usr/bin/perl -w
 
use strict;
use warnings;
use Net::Curl::Easy qw(/^CURLOPT_.*/);;
use JSON;
use Data::Dumper;
 
sub SendNotification
{
    my ($url , $authorisation , $app_id , $contents) = @_;
    my $curl = Net::Curl::Easy->new;
    my $json = JSON->new();
    my $response_body;
 
    my $json_string = $json->encode({ app_id => $app_id ,
                                      included_segments => ["All"] ,
                                      data => { "key1" => "Value 1" } ,
                                      ios_badgeType => "Increase" ,
                                      ios_badgeCount => 1 ,
                                      contents => { en => $contents}
                                    });
 
    $curl->setopt( CURLOPT_URL, $url);
    $curl->setopt( CURLOPT_SSL_VERIFYHOST , 0);
    $curl->setopt( CURLOPT_SSL_VERIFYPEER , 0);
 
    $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8' ,
                                        "Authorization: Basic $authorisation"]);
    $curl->setopt( CURLOPT_POST , 1);
    $curl->setopt( CURLOPT_POSTFIELDS , $json_string);
 
    $curl->setopt( CURLOPT_WRITEDATA , \$response_body);
 
    $curl->perform;
    print Dumper($response_body);
}
 
SendNotification("https://onesignal.com/api/v1/notifications" ,
                 "<< PUT YOUR REST API KEY HERE>>" ,
                 "<< PUT YOUR APP ID KEY HERE >>" ,
                 "Hello World");
 
exit(0);
send = function(params) {

var promise = new Parse.Promise();

var jsonBody = { 
  app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c", 
  included_segments: ["All"],
  contents: {en: "English Message"},
  data: {foo: "bar"}
};

Parse.Cloud.httpRequest({
    method: "POST",
    url: "https://onesignal.com/api/v1/notifications",
    headers: {
      "Content-Type": "application/json;charset=utf-8",
      "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
    },
    body: JSON.stringify(jsonBody)
  }).then(function (httpResponse) {
    promise.resolve(httpResponse)
  },
  function (httpResponse) {
    promise.reject(httpResponse);
});

return promise;
};

exports.send = send;
function SendNewNotification() {

  var jsonBody = {

    app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",

    included_segments: ["All"],

    contents: {en: "English Message"},

  };

  var promise = Spark.getHttp("https://onesignal.com/api/v1/notifications").setHeaders({

    "Content-Type": "application/json;charset=utf-8",

    "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"

  }).postJson(jsonBody);
  

  return promise;

}

var response = SendNewNotification().getResponseJson();

Spark.setScriptData("response", response)
try {
   String jsonResponse;
   
   URL url = new URL("https://onesignal.com/api/v1/notifications");
   HttpURLConnection con = (HttpURLConnection)url.openConnection();
   con.setUseCaches(false);
   con.setDoOutput(true);
   con.setDoInput(true);

   con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
   con.setRequestProperty("Authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
   con.setRequestMethod("POST");

   String strJsonBody = "{"
                      +   "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
                      +   "\"included_segments\": [\"All\"],"
                      +   "\"data\": {\"foo\": \"bar\"},"
                      +   "\"contents\": {\"en\": \"English Message\"}"
                      + "}";
         
   
   System.out.println("strJsonBody:\n" + strJsonBody);

   byte[] sendBytes = strJsonBody.getBytes("UTF-8");
   con.setFixedLengthStreamingMode(sendBytes.length);

   OutputStream outputStream = con.getOutputStream();
   outputStream.write(sendBytes);

   int httpResponse = con.getResponseCode();
   System.out.println("httpResponse: " + httpResponse);

   if (  httpResponse >= HttpURLConnection.HTTP_OK
      && httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
      Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
      jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
      scanner.close();
   }
   else {
      Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
      jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
      scanner.close();
   }
   System.out.println("jsonResponse:\n" + jsonResponse);
   
} catch(Throwable t) {
   t.printStackTrace();
}

Send to a specific segment - Create notification

curl --include \
     --request POST \
     --header "Content-Type: application/json; charset=utf-8" \
     --header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
     --data-binary "{\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\",
\"contents\": {\"en\": \"English Message\"},
\"included_segments\": [\"Active Users\"]}" \
     https://onesignal.com/api/v1/notifications
{
  "app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
  "included_segments": ["Active Users"],
  "data": {"foo": "bar"},
  "contents": {"en": "English Message"}
}
<?PHP
	function sendMessage(){
		$content = array(
			"en" => 'English Message'
			);
		
		$fields = array(
			'app_id' => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
			'included_segments' => array('Active Users'),
			'data' => array("foo" => "bar"),
			'contents' => $content
		);
		
		$fields = json_encode($fields);
    	print("\nJSON sent:\n");
    	print($fields);
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
												   'Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj'));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

		$response = curl_exec($ch);
		curl_close($ch);
		
		return $response;
	}
	
	$response = sendMessage();
	$return["allresponses"] = $response;
	$return = json_encode( $return);
	
	print("\n\nJSON received:\n");
	print($return);
	print("\n");
?>
using System.IO;
using System.Net;
using System.Text;

var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;

request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");

byte[] byteArray = Encoding.UTF8.GetBytes("{"
                                        + "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
                                        + "\"contents\": {\"en\": \"English Message\"},"
                                        + "\"included_segments\": [\"Active Users\"]}");

string responseContent = null;

try {
    using (var writer = request.GetRequestStream()) {
        writer.Write(byteArray, 0, byteArray.Length);
    }

    using (var response = request.GetResponse() as HttpWebResponse) {
        using (var reader = new StreamReader(response.GetResponseStream())) {
            responseContent = reader.ReadToEnd();
        }
    }
}
catch (WebException ex) {
    System.Diagnostics.Debug.WriteLine(ex.Message);
    System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}

System.Diagnostics.Debug.WriteLine(responseContent);
using System.IO;
using System.Net;
using System.Text;

var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;

request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");

var serializer = new JavaScriptSerializer();
var obj = new { app_id = "5eb5a37e-b458-11e3-ac11-000c2940e62c",
               contents = new { en = "English Message" },
               included_segments = new string[] {"Active Users"} };
var param = serializer.Serialize(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);

string responseContent = null;

try {
    using (var writer = request.GetRequestStream()) {
        writer.Write(byteArray, 0, byteArray.Length);
    }

    using (var response = request.GetResponse() as HttpWebResponse) {
        using (var reader = new StreamReader(response.GetResponseStream())) {
            responseContent = reader.ReadToEnd();
        }
    }
}
catch (WebException ex) {
    System.Diagnostics.Debug.WriteLine(ex.Message);
    System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}

System.Diagnostics.Debug.WriteLine(responseContent);
params = {"app_id" => "5eb5a37e-b458-11e3-ac11-000c2940e62c", 
          "contents" => {"en" => "English Message"},
          "included_segments" => ["Active Users"]}
uri = URI.parse('https://onesignal.com/api/v1/notifications')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.path,
                              'Content-Type'  => 'application/json;charset=utf-8',
                              'Authorization' => "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj")
request.body = params.as_json.to_json
response = http.request(request) 
puts response.body
import requests
import json

header = {"Content-Type": "application/json; charset=utf-8",
          "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"}

payload = {"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
           "included_segments": ["Active Users"],
           "contents": {"en": "English Message"}}
 
req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload))
 
print(req.status_code, req.reason)
var sendNotification = function(data) {
  var headers = {
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
  };
  
  var options = {
    host: "onesignal.com",
    port: 443,
    path: "/api/v1/notifications",
    method: "POST",
    headers: headers
  };
  
  var https = require('https');
  var req = https.request(options, function(res) {  
    res.on('data', function(data) {
      console.log("Response:");
      console.log(JSON.parse(data));
    });
  });
  
  req.on('error', function(e) {
    console.log("ERROR:");
    console.log(e);
  });
  
  req.write(JSON.stringify(data));
  req.end();
};

var message = { 
  app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
  contents: {"en": "English Message"},
  included_segments: ["Active Users"]
};

sendNotification(message);
#!/usr/bin/perl -w
 
use strict;
use warnings;
use Net::Curl::Easy qw(/^CURLOPT_.*/);;
use JSON;
use Data::Dumper;
 
sub SendNotification
{
    my ($url , $authorisation , $app_id , $contents) = @_;
    my $curl = Net::Curl::Easy->new;
    my $json = JSON->new();
    my $response_body;
 
    my $json_string = $json->encode({ app_id => $app_id ,
                                      included_segments => ["Active Users"] ,
                                      contents => { en => $contents}
                                    });
 
    $curl->setopt( CURLOPT_URL, $url);
    $curl->setopt( CURLOPT_SSL_VERIFYHOST , 0);
    $curl->setopt( CURLOPT_SSL_VERIFYPEER , 0);
 
    $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8' ,
                                        "Authorization: Basic $authorisation"]);
    $curl->setopt( CURLOPT_POST , 1);
    $curl->setopt( CURLOPT_POSTFIELDS , $json_string);
 
    $curl->setopt( CURLOPT_WRITEDATA , \$response_body);
 
    $curl->perform;
    print Dumper($response_body);
}
 
SendNotification("https://onesignal.com/api/v1/notifications" ,
                 "<< PUT YOUR REST API KEY HERE>>" ,
                 "<< PUT YOUR APP ID KEY HERE >>" ,
                 "Hello World");
 
exit(0);
send = function(params) {

var promise = new Parse.Promise();

var jsonBody = { 
  app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c", 
  included_segments: ["Active Users"],
  contents: {en: "English Message"},
  data: {foo: "bar"}
};

Parse.Cloud.httpRequest({
    method: "POST",
    url: "https://onesignal.com/api/v1/notifications",
    headers: {
      "Content-Type": "application/json;charset=utf-8",
      "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
    },
    body: JSON.stringify(jsonBody)
  }).then(function (httpResponse) {
    promise.resolve(httpResponse)
  },
  function (httpResponse) {
    promise.reject(httpResponse);
});

return promise;
};

exports.send = send;
function SendNewNotification() {

  var jsonBody = {

    app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",

    included_segments: ["Active Users"],

    contents: {en: "English Message"},

  };

  var promise = Spark.getHttp("https://onesignal.com/api/v1/notifications").setHeaders({

    "Content-Type": "application/json;charset=utf-8",

    "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"

  }).postJson(jsonBody);
  

  return promise;

}

var response = SendNewNotification().getResponseJson();

Spark.setScriptData("response", response)
try {
   String jsonResponse;
   
   URL url = new URL("https://onesignal.com/api/v1/notifications");
   HttpURLConnection con = (HttpURLConnection)url.openConnection();
   con.setUseCaches(false);
   con.setDoOutput(true);
   con.setDoInput(true);

   con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
   con.setRequestProperty("Authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
   con.setRequestMethod("POST");

   String strJsonBody = "{"
                      +   "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
                      +   "\"included_segments\": [\"Active Users\"],"
                      +   "\"data\": {\"foo\": \"bar\"},"
                      +   "\"contents\": {\"en\": \"English Message\"}"
                      + "}";
         
   
   System.out.println("strJsonBody:\n" + strJsonBody);

   byte[] sendBytes = strJsonBody.getBytes("UTF-8");
   con.setFixedLengthStreamingMode(sendBytes.length);

   OutputStream outputStream = con.getOutputStream();
   outputStream.write(sendBytes);

   int httpResponse = con.getResponseCode();
   System.out.println("httpResponse: " + httpResponse);

   if (  httpResponse >= HttpURLConnection.HTTP_OK
      && httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
      Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
      jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
      scanner.close();
   }
   else {
      Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
      jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
      scanner.close();
   }
   System.out.println("jsonResponse:\n" + jsonResponse);
   
} catch(Throwable t) {
   t.printStackTrace();
}

Send based on filters/tags - Create notification

curl --include \
     --request POST \
     --header "Content-Type: application/json; charset=utf-8" \
     --header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
     --data-binary "{\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\",
\"contents\": {\"en\": \"English Message\"},
\"filters\": [{\"field\": "\tag\", \"key\": \"level\", \"relation\": \">\", \"value\": \"10\"},{\"operator\": \"OR\"},{\"field\": \"amount_spent\", \"relation\": \">\",\"value\": \"0\"}]}" \
     https://onesignal.com/api/v1/notifications
{
  "app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
  "filters": [
  	{"field": "tag", "key": "level", "relation": "=", "value": "10"}, 
  	{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
  ],
  "data": {"foo": "bar"},
  "contents": {"en": "English Message"}
}
<?PHP
	function sendMessage(){
		$content = array(
			"en" => 'English Message'
			);
		
		$fields = array(
			'app_id' => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
			'filters' => array(array("field" => "tag", "key" => "level", "relation" => "=", "value" => "10"),array("operator" => "OR"),array("field" => "amount_spent", "relation" => "=", "value" => "0")),
			'data' => array("foo" => "bar"),
			'contents' => $content
		);
		
		$fields = json_encode($fields);
    	print("\nJSON sent:\n");
    	print($fields);
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
												   'Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj'));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

		$response = curl_exec($ch);
		curl_close($ch);
		
		return $response;
	}
	
	$response = sendMessage();
	$return["allresponses"] = $response;
	$return = json_encode( $return);
	
	print("\n\nJSON received:\n");
	print($return);
	print("\n");
?>
using System.IO;
using System.Net;
using System.Text;

var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;

request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");

byte[] byteArray = Encoding.UTF8.GetBytes("{"
                                        + "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
                                        + "\"contents\": {\"en\": \"English Message\"},"
                                        + "\"filters\": [{\"field\": \"tag\", \"key\": \"level\", \"relation\": \">\", \"value\": \"10\"},{\"operator\": \"OR\"},{\"field\": \"amount_spent\", \"relation\": \">\",\"value\": \"0\"}]}");

string responseContent = null;

try {
    using (var writer = request.GetRequestStream()) {
        writer.Write(byteArray, 0, byteArray.Length);
    }

    using (var response = request.GetResponse() as HttpWebResponse) {
        using (var reader = new StreamReader(response.GetResponseStream())) {
            responseContent = reader.ReadToEnd();
        }
    }
}
catch (WebException ex) {
    System.Diagnostics.Debug.WriteLine(ex.Message);
    System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}

System.Diagnostics.Debug.WriteLine(responseContent);
using System.IO;
using System.Net;
using System.Text;

var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;

request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");

var serializer = new JavaScriptSerializer();
var obj = new { app_id = "5eb5a37e-b458-11e3-ac11-000c2940e62c",
               contents = new { en = "English Message" },
               filters = new object[] { new { field = "tag", key = "level", value = "10" }, new { @operator = "OR" }, new { field = "amount_spent", relation = ">", value = "0" } } };

                 

var param = serializer.Serialize(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);

string responseContent = null;

try {
    using (var writer = request.GetRequestStream()) {
        writer.Write(byteArray, 0, byteArray.Length);
    }

    using (var response = request.GetResponse() as HttpWebResponse) {
        using (var reader = new StreamReader(response.GetResponseStream())) {
            responseContent = reader.ReadToEnd();
        }
    }
}
catch (WebException ex) {
    System.Diagnostics.Debug.WriteLine(ex.Message);
    System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}

System.Diagnostics.Debug.WriteLine(responseContent);
params = {"app_id" => "5eb5a37e-b458-11e3-ac11-000c2940e62c", 
          "contents" => {"en" => "English Message"},
          "filters" => [
					  	{"field": "tag", "key": "level", "relation": "=", "value": "10"}, 
					  	{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
					  ]
		}
uri = URI.parse('https://onesignal.com/api/v1/notifications')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.path,
                              'Content-Type'  => 'application/json;charset=utf-8',
                              'Authorization' => "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj")
request.body = params.as_json.to_json
response = http.request(request) 
puts response.body
import requests
import json

header = {"Content-Type": "application/json; charset=utf-8",
          "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"}

payload = {"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
           "filters": [
			  	{"field": "tag", "key": "level", "relation": "=", "value": "10"}, 
			  	{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
			],
           "contents": {"en": "English Message"}}
 
req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload))
 
print(req.status_code, req.reason)
var sendNotification = function(data) {
  var headers = {
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
  };
  
  var options = {
    host: "onesignal.com",
    port: 443,
    path: "/api/v1/notifications",
    method: "POST",
    headers: headers
  };
  
  var https = require('https');
  var req = https.request(options, function(res) {  
    res.on('data', function(data) {
      console.log("Response:");
      console.log(JSON.parse(data));
    });
  });
  
  req.on('error', function(e) {
    console.log("ERROR:");
    console.log(e);
  });
  
  req.write(JSON.stringify(data));
  req.end();
};

var message = { 
  app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
  contents: {"en": "English Message"},
  filters: [
	  	{"field": "tag", "key": "level", "relation": "=", "value": "10"}, 
	  	{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
	]
};

sendNotification(message);
#!/usr/bin/perl -w
 
use strict;
use warnings;
use Net::Curl::Easy qw(/^CURLOPT_.*/);;
use JSON;
use Data::Dumper;
 
sub SendNotification
{
    my ($url , $authorisation , $app_id , $contents) = @_;
    my $curl = Net::Curl::Easy->new;
    my $json = JSON->new();
    my $response_body;
 
    my $json_string = $json->encode({ app_id => $app_id ,
                                      filters => [
										  	{"field": "tag", "key": "level", "relation": "=", "value": "10"}, 
										  	{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
										],
                                      contents => { en => $contents}
                                    });
 
    $curl->setopt( CURLOPT_URL, $url);
    $curl->setopt( CURLOPT_SSL_VERIFYHOST , 0);
    $curl->setopt( CURLOPT_SSL_VERIFYPEER , 0);
 
    $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8' ,
                                        "Authorization: Basic $authorisation"]);
    $curl->setopt( CURLOPT_POST , 1);
    $curl->setopt( CURLOPT_POSTFIELDS , $json_string);
 
    $curl->setopt( CURLOPT_WRITEDATA , \$response_body);
 
    $curl->perform;
    print Dumper($response_body);
}
 
SendNotification("https://onesignal.com/api/v1/notifications" ,
                 "<< PUT YOUR REST API KEY HERE>>" ,
                 "<< PUT YOUR APP ID KEY HERE >>" ,
                 "Hello World");
 
exit(0);
send = function(params) {

var promise = new Parse.Promise();

var jsonBody = { 
  app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c", 
  filters: [
  	{"field": "tag", "key": "level", "relation": "=", "value": "10"}, 
  	{"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}
  ],
  contents: {en: "English Message"},
  data: {foo: "bar"}
};

Parse.Cloud.httpRequest({
    method: "POST",
    url: "https://onesignal.com/api/v1/notifications",
    headers: {
      "Content-Type": "application/json;charset=utf-8",
      "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
    },
    body: JSON.stringify(jsonBody)
  }).then(function (httpResponse) {
    promise.resolve(httpResponse)
  },
  function (httpResponse) {
    promise.reject(httpResponse);
});

return promise;
};

exports.send = send;
function SendNewNotification() {

  var jsonBody = {

    app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",

    filters: [

  	  {"field": "tag", "key": "level", "relation": "=", "value": "10"}, 

  	  {"operator": "OR"}, {"field": "amount_spent", "relation": ">", "value": "0"}

    ],

    contents: {en: "English Message"},

  };

  var promise = Spark.getHttp("https://onesignal.com/api/v1/notifications").setHeaders({

    "Content-Type": "application/json;charset=utf-8",

    "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"

  }).postJson(jsonBody);
  

  return promise;

}

var response = SendNewNotification().getResponseJson();

Spark.setScriptData("response", response)
try {
   String jsonResponse;
   
   URL url = new URL("https://onesignal.com/api/v1/notifications");
   HttpURLConnection con = (HttpURLConnection)url.openConnection();
   con.setUseCaches(false);
   con.setDoOutput(true);
   con.setDoInput(true);

   con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
   con.setRequestProperty("Authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
   con.setRequestMethod("POST");

   String strJsonBody = "{"
                      +   "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
                      +   "\"filters\": [{\"field\": \"tag\", \"key\": \"level\", \"relation\": \">\", \"value\": \"10\"},{\"operator\": \"OR\"},{\"field\": \"amount_spent\", \"relation\": \">\",\"value\": \"0\"}],"
                      +   "\"data\": {\"foo\": \"bar\"},"
                      +   "\"contents\": {\"en\": \"English Message\"}"
                      + "}";
         
   
   System.out.println("strJsonBody:\n" + strJsonBody);

   byte[] sendBytes = strJsonBody.getBytes("UTF-8");
   con.setFixedLengthStreamingMode(sendBytes.length);

   OutputStream outputStream = con.getOutputStream();
   outputStream.write(sendBytes);

   int httpResponse = con.getResponseCode();
   System.out.println("httpResponse: " + httpResponse);

   if (  httpResponse >= HttpURLConnection.HTTP_OK
      && httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
      Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
      jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
      scanner.close();
   }
   else {
      Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
      jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
      scanner.close();
   }
   System.out.println("jsonResponse:\n" + jsonResponse);
   
} catch(Throwable t) {
   t.printStackTrace();
}

Send based on OneSignal PlayerIds - Create notification

curl --include \
     --request POST \
     --header "Content-Type: application/json; charset=utf-8" \
     --header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
     --data-binary "{\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\",
\"contents\": {\"en\": \"English Message\"},
\"include_player_ids\": [\"6392d91a-b206-4b7b-a620-cd68e32c3a76\",\"76ece62b-bcfe-468c-8a78-839aeaa8c5fa\",\"8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86\"]}" \
     https://onesignal.com/api/v1/notifications
{
  "app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
  "include_player_ids": ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
  "data": {"foo": "bar"},
  "contents": {"en": "English Message"}
}
<?PHP
	function sendMessage(){
		$content = array(
			"en" => 'English Message'
			);
		
		$fields = array(
			'app_id' => "5eb5a37e-b458-11e3-ac11-000c2940e62c",
			'include_player_ids' => array("6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"),
			'data' => array("foo" => "bar"),
			'contents' => $content
		);
		
		$fields = json_encode($fields);
    	print("\nJSON sent:\n");
    	print($fields);
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
												   'Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj'));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

		$response = curl_exec($ch);
		curl_close($ch);
		
		return $response;
	}
	
	$response = sendMessage();
	$return["allresponses"] = $response;
	$return = json_encode( $return);
	
	print("\n\nJSON received:\n");
	print($return);
	print("\n");
?>
using System.IO;
using System.Net;
using System.Text;

var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;

request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");

byte[] byteArray = Encoding.UTF8.GetBytes("{"
                                        + "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
                                        + "\"contents\": {\"en\": \"English Message\"},"
                                        + "\"include_player_ids\": [\"6392d91a-b206-4b7b-a620-cd68e32c3a76\",\"76ece62b-bcfe-468c-8a78-839aeaa8c5fa\",\"8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86\"]}");

string responseContent = null;

try {
    using (var writer = request.GetRequestStream()) {
        writer.Write(byteArray, 0, byteArray.Length);
    }

    using (var response = request.GetResponse() as HttpWebResponse) {
        using (var reader = new StreamReader(response.GetResponseStream())) {
            responseContent = reader.ReadToEnd();
        }
    }
}
catch (WebException ex) {
    System.Diagnostics.Debug.WriteLine(ex.Message);
    System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}

System.Diagnostics.Debug.WriteLine(responseContent);
using System.IO;
using System.Net;
using System.Text;

var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;

request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");

var serializer = new JavaScriptSerializer();
var obj = new { app_id = "5eb5a37e-b458-11e3-ac11-000c2940e62c",
               contents = new { en = "English Message" },
               include_player_ids = new string[] {"6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"} };

                 

var param = serializer.Serialize(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);

string responseContent = null;

try {
    using (var writer = request.GetRequestStream()) {
        writer.Write(byteArray, 0, byteArray.Length);
    }

    using (var response = request.GetResponse() as HttpWebResponse) {
        using (var reader = new StreamReader(response.GetResponseStream())) {
            responseContent = reader.ReadToEnd();
        }
    }
}
catch (WebException ex) {
    System.Diagnostics.Debug.WriteLine(ex.Message);
    System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}

System.Diagnostics.Debug.WriteLine(responseContent);
params = {"app_id" => "5eb5a37e-b458-11e3-ac11-000c2940e62c", 
          "contents" => {"en" => "English Message"},
          "include_player_ids" => ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"]
		}
uri = URI.parse('https://onesignal.com/api/v1/notifications')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.path,
                              'Content-Type'  => 'application/json;charset=utf-8',
                              'Authorization' => "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj")
request.body = params.as_json.to_json
response = http.request(request) 
puts response.body
import requests
import json

header = {"Content-Type": "application/json; charset=utf-8",
          "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"}

payload = {"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
           "include_player_ids": ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
           "contents": {"en": "English Message"}}
 
req = requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload))
 
print(req.status_code, req.reason)
var sendNotification = function(data) {
  var headers = {
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
  };
  
  var options = {
    host: "onesignal.com",
    port: 443,
    path: "/api/v1/notifications",
    method: "POST",
    headers: headers
  };
  
  var https = require('https');
  var req = https.request(options, function(res) {  
    res.on('data', function(data) {
      console.log("Response:");
      console.log(JSON.parse(data));
    });
  });
  
  req.on('error', function(e) {
    console.log("ERROR:");
    console.log(e);
  });
  
  req.write(JSON.stringify(data));
  req.end();
};

var message = { 
  app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
  contents: {"en": "English Message"},
  include_player_ids: ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"]
};

sendNotification(message);
#!/usr/bin/perl -w
 
use strict;
use warnings;
use Net::Curl::Easy qw(/^CURLOPT_.*/);;
use JSON;
use Data::Dumper;
 
sub SendNotification
{
    my ($url , $authorisation , $app_id , $contents) = @_;
    my $curl = Net::Curl::Easy->new;
    my $json = JSON->new();
    my $response_body;
 
    my $json_string = $json->encode({ app_id => $app_id ,
                                      include_player_ids => ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
                                      contents => { en => $contents}
                                    });
 
    $curl->setopt( CURLOPT_URL, $url);
    $curl->setopt( CURLOPT_SSL_VERIFYHOST , 0);
    $curl->setopt( CURLOPT_SSL_VERIFYPEER , 0);
 
    $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8' ,
                                        "Authorization: Basic $authorisation"]);
    $curl->setopt( CURLOPT_POST , 1);
    $curl->setopt( CURLOPT_POSTFIELDS , $json_string);
 
    $curl->setopt( CURLOPT_WRITEDATA , \$response_body);
 
    $curl->perform;
    print Dumper($response_body);
}
 
SendNotification("https://onesignal.com/api/v1/notifications" ,
                 "<< PUT YOUR REST API KEY HERE>>" ,
                 "<< PUT YOUR APP ID KEY HERE >>" ,
                 "Hello World");
 
exit(0);
send = function(params) {

var promise = new Parse.Promise();

var jsonBody = { 
  app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c", 
  include_player_ids: ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],
  contents: {en: "English Message"},
  data: {foo: "bar"}
};

Parse.Cloud.httpRequest({
    method: "POST",
    url: "https://onesignal.com/api/v1/notifications",
    headers: {
      "Content-Type": "application/json;charset=utf-8",
      "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
    },
    body: JSON.stringify(jsonBody)
  }).then(function (httpResponse) {
    promise.resolve(httpResponse)
  },
  function (httpResponse) {
    promise.reject(httpResponse);
});

return promise;
};

exports.send = send;

function SendNewNotification() {

  var jsonBody = {

    app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",

    include_player_ids: ["6392d91a-b206-4b7b-a620-cd68e32c3a76","76ece62b-bcfe-468c-8a78-839aeaa8c5fa","8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"],

    contents: {en: "English Message"},

  };

  var promise = Spark.getHttp("https://onesignal.com/api/v1/notifications").setHeaders({

    "Content-Type": "application/json;charset=utf-8",

    "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"

  }).postJson(jsonBody);
  

  return promise;

}

var response = SendNewNotification().getResponseJson();

Spark.setScriptData("response", response)
try {
   String jsonResponse;
   
   URL url = new URL("https://onesignal.com/api/v1/notifications");
   HttpURLConnection con = (HttpURLConnection)url.openConnection();
   con.setUseCaches(false);
   con.setDoOutput(true);
   con.setDoInput(true);

   con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
   con.setRequestProperty("Authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
   con.setRequestMethod("POST");

   String strJsonBody = "{"
                      +   "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
                      +   "\"include_player_ids\": [\"6392d91a-b206-4b7b-a620-cd68e32c3a76\",\"76ece62b-bcfe-468c-8a78-839aeaa8c5fa\",\"8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86\"],"
                      +   "\"data\": {\"foo\": \"bar\"},"
                      +   "\"contents\": {\"en\": \"English Message\"}"
                      + "}";
         
   
   System.out.println("strJsonBody:\n" + strJsonBody);

   byte[] sendBytes = strJsonBody.getBytes("UTF-8");
   con.setFixedLengthStreamingMode(sendBytes.length);

   OutputStream outputStream = con.getOutputStream();
   outputStream.write(sendBytes);

   int httpResponse = con.getResponseCode();
   System.out.println("httpResponse: " + httpResponse);

   if (  httpResponse >= HttpURLConnection.HTTP_OK
      && httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
      Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
      jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
      scanner.close();
   }
   else {
      Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
      jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
      scanner.close();
   }
   System.out.println("jsonResponse:\n" + jsonResponse);
   
} catch(Throwable t) {
   t.printStackTrace();
}

Results - Create notification

{
  "id": "458dcec4-cf53-11e3-add2-000c2940e62c",
  "recipients": 3
}
{
  "errors": ["Notification content must not be null for any languages."]
}
// Returned if using include_player_ids and some were valid and others were not.
// Please process theses on your server and removing them from your database if your tracking them.

{
  "errors": {
    "invalid_player_ids" : ["5fdc92b2-3b2a-11e5-ac13-8fdccfe4d986", "00cb73f8-5815-11e5-ba69-f75522da5528"]
  }
}
{"id": "", "recipients": 0, "errors": ["All included players are not subscribed"]}

Cancel notification

Stop a scheduled or currently outgoing notification

 
delete https://onesignal.com/api/v1/notifications/:id?app_id=:app_id
 

Used to stop a scheduled or currently outgoing notification.

Requires Authentication Key

Requires your OneSignal App Auth Key, available in Keys & IDs, unless the notification was created using include_player_ids and targeting only one user.

Path Parameters

Parameter
Type
Description

id

String

Required Notification id

app_id

String

Required App id

Example Code - Cancel notification

curl --include \
		 --request DELETE \
     --header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
 https://onesignal.com/api/v1/notifications/{notificationId}?app_id={appId}

Result Format - Cancel notification

{'success': "true"}

View apps

View the details of all of your current OneSignal apps

 
get https://onesignal.com/api/v1/apps
 

Requires Authentication Key

Requires your OneSignal User Auth Key, available in Keys & IDs.

Example Code - View apps

curl --include \
     --header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
 https://onesignal.com/api/v1/apps

Result Format - View apps

[
  {
    id: "92911750-242d-4260-9e00-9d9034f139ce",
    name: "Your app 1",
    players: 150,
    messagable_players: 143,
    updated_at: "2014-04-01T04:20:02.003Z",
    created_at: "2014-04-01T04:20:02.003Z",
    gcm_key: "a gcm push key",
    chrome_key: "A Chrome Web Push GCM key",
    chrome_web_origin: "Chrome Web Push Site URL",
    chrome_web_gcm_sender_id: "Chrome Web Push GCM Sender ID",
    chrome_web_default_notification_icon: "http://yoursite.com/chrome_notification_icon",
    chrome_web_sub_domain:"your_site_name",
    apns_env: "sandbox",
    apns_certificates: "Your apns certificate",
    safari_apns_cetificate: "Your Safari APNS certificate",
    safari_site_origin: "The homename for your website for Safari Push, including http or https",
    safari_push_id: "The certificate bundle ID for Safari Web Push",
    safari_icon_16_16: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/16x16.png",
    safari_icon_32_32: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/16x16@2.png",
    safari_icon_64_64: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/32x32@2x.png",
    safari_icon_128_128: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/128x128.png",
    safari_icon_256_256: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/128x128@2x.png",
    site_name: "The URL to your website for Web Push",  
    basic_auth_key: "NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
  },
  {
    id: "e4e87830-b954-11e3-811d-f3b376925f15",
    name: "Your app 2",
    players: 100,
    messagable_players: 80,
    updated_at: "2014-04-01T04:20:02.003Z",
    created_at: "2014-04-01T04:20:02.003Z",
    gcm_key: "a gcm push key",
    chrome_key: "A Chrome Web Push GCM key",
    chrome_web_origin: "Chrome Web Push Site URL",
    chrome_web_gcm_sender_id: "Chrome Web Push GCM Sender ID",
    chrome_web_default_notification_icon: "http://yoursite.com/chrome_notification_icon",
    chrome_web_sub_domain:"your_site_name",
    apns_env: "sandbox",
    apns_certificates: "Your apns certificate",
    safari_apns_cetificate: "Your Safari APNS certificate",
    safari_site_origin: "The homename for your website for Safari Push, including http or https",
    safari_push_id: "The certificate bundle ID for Safari Web Push",
    safari_icon_16_16: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/16x16.png",
    safari_icon_32_32: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/16x16@2.png",
    safari_icon_64_64: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/32x32@2x.png",
    safari_icon_128_128: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/128x128.png",
    safari_icon_256_256: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/128x128@2x.png",
    site_name: "The URL to your website for Web Push",  
    basic_auth_key: "NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
  }
]
{}

View an app

View the details of a single OneSignal app

 
get https://onesignal.com/api/v1/apps/:id
 

Requires Authentication Key

Requires your OneSignal User Auth Key, available in Keys & IDs.

Path Parameters

Parameter
Type
Description

id

String

Required An app id

Example Code - View an app

curl --include \
     --header "Content-Type: application/json" \
     --header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
 https://onesignal.com/api/v1/apps/e4e87830-b954-11e3-811d-f3b376925f15
		$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/apps/YOUR_APP_ID");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
                           'Authorization: Basic YOUR_USER_AUTH_KEY'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    $response = curl_exec($ch);
		$response = json_decode($response, true);
    curl_close($ch);

Result Format - View an app

{
  id: "92911750-242d-4260-9e00-9d9034f139ce",
  name: "Your app 1",
  players: 150,
  messageable_players: 143,
  updated_at: "2014-04-01T04:20:02.003Z",
  created_at: "2014-04-01T04:20:02.003Z",
  gcm_key: "a gcm push key",
  chrome_key: "A Chrome Web Push GCM key",
  chrome_web_origin: "Chrome Web Push Site URL",
  chrome_web_gcm_sender_id: "Chrome Web Push GCM Sender ID",
  chrome_web_default_notification_icon: "http://yoursite.com/chrome_notification_icon",
  chrome_web_sub_domain:"your_site_name",
  apns_env: "production",
  apns_certificates: "Your apns certificate",
  safari_apns_cetificate: "Your Safari APNS certificate",
  safari_site_origin: "The homename for your website for Safari Push, including http or https",
  safari_push_id: "The certificate bundle ID for Safari Web Push",
  safari_icon_16_16: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/16x16.png",
  safari_icon_32_32: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/16x16@2.png",
  safari_icon_64_64: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/32x32@2x.png",
  safari_icon_128_128: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/128x128.png",
  safari_icon_256_256: "http://onesignal.com/safari_packages/92911750-242d-4260-9e00-9d9034f139ce/128x128@2x.png",
  site_name: "The URL to your website for Web Push",  
  basic_auth_key: "NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
}

Create an app

Creates a new OneSignal app

 
post https://onesignal.com/api/v1/apps
 

Requires Authentication Key

Requires your OneSignal User Auth Key, available in Keys & IDs.

Body Parameters - Create an app

Parameter
Type
Description

name

String

Required The name of your new app, as displayed on your apps list on the dashboard. This can be renamed later.

apns_env

String

iOS - Either sandbox or production

apns_p12

String

iOS - Your apple push notification p12 certificate file, converted to a string and Base64 encoded.

apns_p12_password

String

iOS - Password for the apns_p12 file

gcm_key

String

Android - Your Google Push Messaging Auth Key

android_gcm_sender_id

String

Android - Your Google Project number. Also know as Sender ID.

chrome_web_origin

String

Chrome, Firefox - The URL to your website. This field is required if you wish to enable web push and specify other web push parameters.

chrome_web_default_notification_icon

String

Chrome - Your default notification icon. Should be 80x80 pixels.

chrome_web_sub_domain

String

Chrome - A subdomain of your choice in order to support Chrome Web Push on non-HTTPS websites. This field must be set in order for the chrome_web_gcm_sender_id property to be processed.

safari_apns_p12

String

Safari - Your apple push notification p12 certificate file for Safari Push Notifications, converted to a string and Base64 encoded.

safari_apns_p12_password

String

Safari - Password for safari_apns_p12 file

site_name

String

Safari - The URL to your website

safari_site_origin

String

Safari - The hostname to your website including http(s)://

safari_icon_256_256

String

Safari - A url for a 256x256 png notification icon. This is the only Safari icon URL you need to provide.

chrome_key

String

Not for web push
Your Google Push Messaging Auth Key if you use Chrome Apps / Extensions.

Example Code - Create an app

This method is used to create new apps in your OneSignal account. It allows you to specify your APNS and GCM auth tokens as well.

curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
     --data-binary "{\"name\" : \"Your app 1\",
\"apns_env\": \"production\",
\"apns_p12\": \"asdsadcvawe223cwef...\",
\"apns_p12_password\": \"FooBar\",
\"gcm_key\": \"a gcm push key\"}" \
     https://onesignal.com/api/v1/apps

Result Format - Create an app

{
  id: "e4e87830-b954-11e3-811d-f3b376925f15",
  name: "Your app 1",
  players: 0,
  messagable_players: 0,
  updated_at: "2014-04-01T04:20:02.003Z",
  created_at: "2014-04-01T04:20:02.003Z",
  gcm_key: "a gcm push key",
  chrome_web_origin: "Chrome Web Push Site URL",
  chrome_web_default_notification_icon: "http://yoursite.com/chrome_notification_icon",
  chrome_web_sub_domain:"your_site_name",
  apns_env: "production",
  apns_certificates: "Your apns certificate",
  safari_apns_cetificate: "Your Safari APNS certificate",
  safari_site_origin: "The homename for your website for Safari Push, including http or https",
  safari_push_id: "The certificate bundle ID for Safari Web Push",
  safari_icon_16_16: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/16x16.png",
  safari_icon_32_32: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/16x16@2.png",
  safari_icon_64_64: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/32x32@2x.png",
  safari_icon_128_128: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/128x128.png",
  safari_icon_256_256: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/128x128@2x.png",
  site_name: "The URL to your website for Web Push",  
  basic_auth_key: "NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
} 

Update an app

Updates the name or configuration settings of an existing OneSignal app

 
put https://onesignal.com/api/v1/apps/:id
 

This method can be used to update the name or configuration settings of one of your existing apps.

Same as POST /apps

The supported parameters are the same as the parameters for creating an application.

Updating Some Platforms Requires All Attributes To Be Set

Updating some platforms like Safari web push requires all parameters to be set (even if they are unchanged) in order for the update to be processed.

  • To update only your app name, you can pass in only a new app name parameter.
  • To update Android, be sure to pass in gcm_key.
  • To update Chrome Apps & Extensions, be sure to pass in chrome_key.
  • To update Chrome web push, be sure to pass in chrome_web_origin.
  • To update Safari web push, you must pass in all of these parameters: safari_apns_p12, safari_apns_p12_password, site_name, and safari_site_origin. Most users use our auto-generated Safari web ID. If you use our auto-generated Safari web ID, please set safari_apns_p12 to "" and safari_apns_p12_password to "".
  • To update iOS, you must pass in apns_env and apns_p12.

Requires Authentication Key

Requires your OneSignal User Auth Key, available in Keys & IDs.

Example Code - Update an app

curl --include \
     --request PUT \
     --header "Content-Type: application/json" \
     --header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
     --data-binary "{\"name\" : \"Your app 1\",
\"apns_env\": \"production\",
\"apns_p12\": \"asdsadcvawe223cwef...\",
\"apns_p12_password\": \"FooBar\",
\"gcm_key\": \"a gcm push key\"}" \
     https://onesignal.com/api/v1/apps/e4e87830-b954-11e3-811d-f3b376925f15

Result Format - Update an app

{
  id: "e4e87830-b954-11e3-811d-f3b376925f15",
  name: "Your app 1",
  players: 0,
  messagable_players: 0,
  updated_at: "2014-04-01T04:20:02.003Z",
  created_at: "2014-04-01T04:20:02.003Z",
  gcm_key: "a gcm push key",
  chrome_key: "A Chrome Web Push GCM key",
  chrome_web_origin: "Chrome Web Push Site URL",
  chrome_web_default_notification_icon: "http://yoursite.com/chrome_notification_icon",
  chrome_web_sub_domain:"your_site_name",
  apns_env: "production",
  apns_certificates: "Your apns certificate",
  safari_apns_cetificate: "Your Safari APNS certificate",
  safari_site_origin: "The homename for your website for Safari Push, including http or https",
  safari_push_id: "The certificate bundle ID for Safari Web Push",
  safari_icon_16_16: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/16x16.png",
  safari_icon_32_32: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/16x16@2.png",
  safari_icon_64_64: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/32x32@2x.png",
  safari_icon_128_128: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/128x128.png",
  safari_icon_256_256: "http://onesignal.com/safari_packages/e4e87830-b954-11e3-811d-f3b376925f15/128x128@2x.png",
  site_name: "The URL to your website for Web Push",  
  basic_auth_key: "NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
}  

View devices

View the details of multiple devices in one of your OneSignal apps

 
gethttps://onesignal.com/api/v1/players?app_id=:app_id&limit=:limit&offset=:offset
 

Requires Authentication Key

Requires your OneSignal App Auth Key, available in Keys & IDs.

Unavailable for Apps > 100,000 users

For performance reasons, this method is not available for larger apps. Larger apps should use the CSV export API endpoint, which is much more performant.

Query Parameters

Parameter
Type
Description

app_id

String

Required The app ID that you want to view devices from

limit

String

How many devices to return. Max is 300. Default is 300

offset

String

Result offset. Default is 0. Results are sorted by id;

Response Parameters

Parameter
Type
Description

invalid_identifier

boolean

If true, this is the equivalent of a user being Unsubscribed (as seen in All Users).

Example Code - View devices

See our PUT player call for a description of the fields listed below in the example.

curl --include \
     --header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
     "https://onesignal.com/api/v1/players?app_id={appId}&limit=300&offset=0"
<?php

// NOTE: Only fetches the first 300 devices.
//       Will need to add looping with offset to get all devices.
function getDevices(){ 
  $app_id = "YOUR_ONESIGNAL_APP_ID_HERE";
  $ch = curl_init(); 
  curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/players?app_id=" . $app_id); 
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 
                                             'Authorization: Basic YOUR_ONESIGNAL_APP_AUTH_KEY_HERE')); 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
  curl_setopt($ch, CURLOPT_HEADER, FALSE);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  $response = curl_exec($ch); 
  curl_close($ch); 
  return $response; 
}

$response = getDevices(); 
$return["allresponses"] = $response; 
$return = json_encode( $return); 
print("\n\nJSON received:\n"); 
print($return); 
print("\n") 
?>

Result Format - View devices

{
 "total_count":3,
 "offset":2,
 "limit":2,
 "players":
 [
    {
        "identifier":"ce777617da7f548fe7a9ab6febb56cf39fba6d382000c0395666288d961ee566",
      "session_count":1,
      "language":"en",
      "timezone":-28800,
      "game_version":"1.0",
      "device_os":"7.0.4",
      "device_type":0,
      "device_model":"iPhone",
      "ad_id":null,
      "tags":{"a":"1","foo":"bar"},
      "last_active":1395096859,
      "amount_spent":0.0,
      "created_at":1395096859,
      "invalid_identifier":false,
      "badge_count": 0
    }
 ]
}

View device

View the details of an existing device in one of your OneSignal apps

 
gethttps://onesignal.com/api/v1/players/:id
 

See our Add a device documentation for descriptions of the fields.

Path Parameters

Parameter
Type
Description

id

String

Player's OneSignal ID

Query Parameters

Parameter
Type
Description

app_id

String

Your app_id for this device

Example Code - View device

curl --include \ 
https://onesignal.com/api/v1/players/ffffb794-ba37-11e3-8077-031d62f86ebf?app_id=f69739a6-3ef1-4aaf-90d9-fec35b7c9c13

Result Format - View device

{
  "identifier":"ce777617da7f548fe7a9ab6febb56cf39fba6d382000c0395666288d961ee566",
  "session_count":1,
  "language":"en",
  "timezone":-28800,
  "game_version":"1.0",
  "device_os":"7.0.4",
  "device_type":0,
  "device_model":"iPhone",
  "ad_id":null,
  "tags":{"a":"1","foo":"bar"},
  "last_active":1395096859,
  "amount_spent":0.0,
  "created_at":1395096859,
  "invalid_identifier":false,
  "badge_count": 0
}

Add a device

Register a new device to one of your OneSignal apps

 
posthttps://onesignal.com/api/v1/players
 

Don't use this

This API endpoint is designed to be used from our open source Mobile and Web Push SDKs. It is not designed for developers to use it directly, unless instructed to do so by OneSignal support.

If you use this method instead of our SDKs, many OneSignal features such as conversion tracking, timezone tracking, language detection, and rich-push won't work out of the box. It will also make it harder to identify possible setup issues.

This method is used to register a new device with OneSignal.

If a device is already registered with the specified identifier, then this will update the existing device record instead of creating a new one.

The returned player is a player / user ID. Use the returned ID to send push notifications to this specific user later, or to include this player when sending to a set of users.

iOS

Must set test_type to 1 when building your iOS app as development. Omit this field in your production app builds.

Body Parameters - Add a device

Parameter
Type
Description

app_id

String

Required Your OneSignal App Id found in Keys & IDs

device_type

Int

Required The device's platform:
0 = iOS
1 = Android
2 = Amazon
3 = WindowsPhone (MPNS)
4 = Chrome Apps / Extensions
5 = Chrome Web Push
6 = WindowsPhone (WNS)
7 = Safari
8 = Firefox
9 = MacOS

identifier

String

Recommended Push notification identifier from Google or Apple. For Apple push identifiers, you must strip all non alphanumeric characters. Example: ce777617da7f548fe7a9ab6febb56

language

String

Recommended Language code. Typically lower case two letters, except for Chinese where it must be one of zh-Hans or zh-Hant. Example: en

timezone

Int

Recommended Number of seconds away from UTC. Example: -28800

game_version

String

Recommended Version of your app. Example: 1.1

device_model

String

Recommended Device make and model. Example: iPhone5,1

device_os

String

Recommended Device operating system version. Example: 7.0.4

ad_id

String

Recommended The ad id for the device's platform:
Android = Advertising Id
iOS = identifierForVendor
WP8.0 = DeviceUniqueId
WP8.1 = AdvertisingId

sdk

String

Recommended Name and version of the plugin that's calling this API method (if any)

session_count

Int

Number of times the user has played the game, defaults to 1

tags

Hash

Custom tags for the player. Only support string key value pairs. Does not support arrays or other nested objects. Example: {"foo":"bar","this":"that"}

amount_spent

String

Amount the user has spent in USD, up to two decimal places

created_at

Int

Unixtime when the player joined the game

playtime

Int

Seconds player was running your app.

badge_count

Int

Current iOS badge count displayed on the app icon

last_active

Int

Unixtime when the player was last active

notification_types

Int

1 = subscribed
-2 = unsubscribed

iOS - These values are set each time the user opens the app from the SDK. Use the SDK function set Subscription instead.

Android - You may set this but you can no longer use the SDK method setSubscription later in your app as it will create synchronization issues.

test_type

Int

This is used in deciding whether to use your iOS Sandbox or Production push certificate when sending a push when both have been uploaded. Set to the iOS provisioning profile that was used to build your app.
1 = Development
2 = Ad-Hoc
Omit this field for App Store builds.

long

Double

Longitude of the device, used for geotagging to segment on.

lat

Double

Latitude of the device, used for geotagging to segment on.

country

String

Country code in the ISO 3166-1 Alpha 2 format

Example Code - Add a device

curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --data-binary "{\"app_id\" : \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\",
\"identifier\":\"ce777617da7f548fe7a9ab6febb56cf39fba6d382000c0395666288d961ee566\",
\"language\":\"en\",
\"timezone\":-28800,
\"game_version\":\"1.0\",
\"device_os\":\"7.0.4\",
\"device_type\":0,
\"device_model\":\"iPhone 8,2\",
\"tags\":{\"a\":\"1\",\"foo\":\"bar\"}}" \
     https://onesignal.com/api/v1/players
<?PHP
$fields = array( 
'app_id' => "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", 
'identifier' => "ce777617da7f548fe7a9ab6febb56cf39fba6d382000c0395666288d961ee566", 
'language' => "en", 
'timezone' => "-28800", 
'game_version' => "1.0", 
'device_os' => "9.1.3", 
'device_type' => "0", 
'device_model' => "iPhone 8,2", 
'tags' => array("foo" => "bar") 
); 

$fields = json_encode($fields); 
print("\nJSON sent:\n"); 
print($fields); 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/players"); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_HEADER, FALSE); 
curl_setopt($ch, CURLOPT_POST, TRUE); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 

$response = curl_exec($ch); 
curl_close($ch); 

$return["allresponses"] = $response; 
$return = json_encode( $return); 

print("\n\nJSON received:\n"); 
print($return); 
print("\n");

?>

Result Format - Add a device

{"success": true, "id": "ffffb794-ba37-11e3-8077-031d62f86ebf" }

Edit device

Update an existing device in one of your OneSignal apps

 
puthttps://onesignal.com/api/v1/players/:id
 

Warning - Web / Mobile SDK

Instead of using this REST API call we recommend using our Mobile / Web SDK methods. Changes values with this REST API call may create synchronization issues with the SDK.

Path Parameters

Parameter
Type
Description

id

String

Required The device's OneSignal ID

Body Parameters

Parameter
Type
Description

app_id

String

Required Your OneSignal App Id found in Keys & IDs

identifier

String

Push notification identifier from Google or Apple. For Apple push identifiers, you must strip all non alphanumeric characters. Example: ce777617da7f548fe7a9ab6febb56

language

String

Language code. Typically lower case two letters, except for Chinese where it must be one of zh-Hans or zh-Hant. Example: en

timezone

Int

Number of seconds away from UTC. Example: -28800

game_version

String

Version of your app. Example: 1.1

device_model

String

Device make and model. Example: iPhone5,1

device_os

String

Device operating system version. Example: 7.0.4

ad_id

String

The ad id for the device's platform:
Android = Advertising Id
iOS = identifierForVendor
WP8.0 = DeviceUniqueId
WP8.1 = AdvertisingId

sdk

String

Name and version of the sdk/plugin that's calling this API method (if any)

session_count

Int

Number of times the user has played the game, defaults to 1

tags

Hash

Custom tags for the player. Only support string key value pairs. Does not support arrays or other nested objects. Example: {"foo":"bar","this":"that"}

amount_spent

String

Amount the user has spent in USD, up to two decimal places

created_at

Int

Unixtime when the player joined the game

playtime

Int

Seconds player was running your app.

badge_count

Int

Current iOS badge count displayed on the app icon

last_active

Int

Unixtime when the player was last active

notification_types

Int

1 = subscribed
-2 = unsubscribed

iOS - These values are set each time the user opens the app from the SDK. Use the SDK function set Subscription instead.

Android - You may set this but you can no longer use the SDK method setSubscription later in your app as it will create synchronization issues.

test_type

Int

This is used in deciding whether to use your iOS Sandbox or Production push certificate when sending a push when both have been uploaded. Set to the iOS provisioning profile that was used to build your app.
1 = Development
2 = Ad-Hoc
Omit this field for App Store builds.

long

Double

Longitude of the device, used for geotagging to segment on.

lat

Double

Latitude of the device, used for geotagging to segment on.

country

String

Country code in the ISO 3166-1 Alpha 2 format

Deleting Tags

To delete a tag, include its key and set its value to blank. Omitting a key/value will not delete it.

For example, if I wanted to delete two existing tanks rank and category while simultaneously adding a new tag class, the tags JSON would look like the following:

"tags": {
           "rank": "",
           "category": "",
           "class": "my_new_value"
        }

Example Code - Edit device

curl --include \
     --request PUT \
     --header "Content-Type: application/json" \
     --data-binary "{\"app_id\" : \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\",
\"language\":\"es\",
\"timezone\":-28800,
\"game_version\":\"1.0\",
\"device_os\":\"7.0.4\",
\"device_type\":0,
\"device_model\":\"iPhone\",
\"tags\":{\"a\":\"1\",\"foo\":\"\"}}" \
     https://onesignal.com/api/v1/players/:id
<?PHP
$playerID = '8dee0e23-410d-4a9a-b8ce-bfe4c5257ccc';
$fields = array( 
'app_id' => '02b297e7-abb5-4e7e-9c2a-9ce7e2c82ff5', 
'tags' => array('OneSignal_Example_Tag' => 'YES')
); 
$fields = json_encode($fields); 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, 'https://onesignal.com/api/v1/players/'.$playerID); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
$response = curl_exec($ch); 
curl_close($ch); 

$resultData = json_decode($response, true);
echo $resultData;
?>

Result Format - Edit device

{"success": true }

New session

Update a device's session information

 
posthttps://onesignal.com/api/v1/players/:id/on_session
 

This method should be called when a device opens your app after they are already registered. This method will automatically increment the player's session_count, and should also be used to update any fields that may have changed (such as language or timezone).

Requires Authentication Key

Requires your OneSignal User Auth Key, available in Keys & IDs.

Body Parameters - New session

Parameter
Type
Description

identifier

String

Recommended Push notification identifier from Google or Apple. For Apple push identifiers, you must strip all non alphanumeric characters. Example: ce777617da7f548fe7a9ab6febb56

language

String

Recommended Language code. Typically lower case two letters, except for Chinese where it must be one of zh-Hans or zh-Hant. Example: en

timezone

Int

Recommended Number of seconds away from UTC. Example: -28800

game_version

String

Recommended Version of your app. Example: 1.1

device_os

String

Recommended Device operating system version. Example: 7.0.4

ad_id

String

Recommended The ad id for the device's platform:
Android = Advertising Id
iOS = identifierForVendor
WP8.0 = DeviceUniqueId
WP8.1 = AdvertisingId

sdk

String

Recommended Name and version of sdk/plugin that's calling this method.

tags

Object

Custom tags for the player. Only support string key value pairs. Does not support arrays or other nested objects. Example: {"foo":"bar","this":"that"}

Example Code - New session

curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --data-binary "{\"language\":\"es\",
\"timezone\":-28800,
\"game_version\":\"1.0\",
\"device_os\":\"7.0.4\"}" \
     https://onesignal.com/api/v1/players/:id/on_session

Result Format - New session

{"success": true }

New purchase

Track a new purchase in your app

 
posthttps://onesignal.com/api/v1/players/:id/on_purchase
 

This will increment the player's amount_spent.

Body Parameters - New purchase

Parameter
Type
Description

purchases

Array

Required An array of purchases, each with the properties listed below.

purchases[sku]

String

Required The unique identifier of the purchased item.

purchases[amount]

Double

Required The amount, in USD, spent purchasing the item.

purchases[iso]

String

Required The 3-letter ISO 4217 currency code. Required for correct storage and conversion of amount.

existing

Boolean

Pass true on the first run of your app if you're tracking existing non-consumable purchases. This prevents tracking the same purchases more than once if the user re-installs your app.

Example Code - New purchase

curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --data-binary "{\"purchases\": [{\"sku\": \"SKU123\", \"iso\": \"USD\", \"amount\": \"0.99\"}]}" \
     https://onesignal.com/api/v1/players/:id/on_purchase
{
  "purchases": 
    [{"sku": "SKU123",
    "iso": "USD",
    "amount": "0.99"}]
}

Result Format - New purchase

{"success": true }

Increment session length

Update a device's session length upon app resuming

 
posthttps://onesignal.com/api/v1/players/:id/on_focus
 

Call this method when the app is resumed or placed into from standby.

The active_time field should be set to the duration between the last on_focus call since the app was opened. If no previous on_focus was called, then the duration should be either the time since POST /players/:id/on_session or POST /players were called.

Body Parameters - Increment session length

Parameter
Type
Description

state

String

Required Set to "ping"

active_time

Int

Required The lesser of: The number of seconds since either: 1. on_focus was last called OR 2. on_session or the device first registered (POST /players)

Example Code - Increment session length

curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --data-binary "{\"state\": \"ping\",
 \"active_time\": 60}" \
     https://onesignal.com/api/v1/players/:id/on_focus

Result Format - Increment session length

{"success": true }

CSV export

Generate a compressed CSV export of all of your current user data

 
posthttps://onesignal.com/api/v1/players/csv_export?app_id=:app_id
 

This method can be used to generate a compressed CSV export of all of your current user data. It is a much faster alternative than retrieving this data using the ./players API endpoint.

You can test if it is complete by making a GET request to the csv_file_url value. If the file is not ready, a 404 error will be returned. Otherwise the file itself will be returned.

The file will be compressed using GZip.

The file may take several minutes to generate depending on the number of users in your app.

Requires Authentication Key

Requires your OneSignal App Auth Key, available in Keys & IDs.

Query Parameters

Parameter
Type
Description

app_id

String

Required The app ID that you want to export devices from

Body Parameters - CSV export

extra_fields

Array of Strings

iOS Android
Additional fields that you wish to include. Currently supports location, country, and rooted.

Example Code - CSV export

curl -X POST -H "Authorization: Basic <YOUR-APP-REST-API-KEY>" -H "Content-Type: application/json" -d '{
    "extra_fields": ["location", "rooted"]
}' "https://onesignal.com/api/v1/players/csv_export?app_id=<YOUR-APP-ID>"

Result Format - CSV export

{ "csv_file_url": "https://onesignal.com/csv_exports/b2f7f966-d8cc-11e4-bed1-df8f05be55ba/users_184948440ec0e334728e87228011ff41_2015-11-10.csv.gz" }
{}

View notification

View the details of a single notification

 
gethttps://onesignal.com/api/v1/notifications/:id?app_id=:app_id
 

Requires Authentication Key

Requires your OneSignal User Auth Key, available in Keys & IDs.

Path Parameters

Parameter
Type
Description

id

String

Required Notification ID

app_id

String

Required App ID

Example Code - View notification

curl --include \
     --header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
 https://onesignal.com/api/v1/notifications/{notificationId}?app_id={appId}
<?PHP
		$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications/YOUR_NOTIFICATION_ID?app_id=YOUR_APP_ID");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
                           'Authorization: Basic AUTH_KEY'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    $response = curl_exec($ch);
    curl_close($ch);
		$return["allresponses"] = $response;
  	$return = json_encode( $return);
  
	  print("\n\nJSON received:\n");
	  print($return);
	  print("\n");
?>

Returned Fields

  • remaining - Number of notifications that have not been sent out yet. This can mean either our system is still processing the notification or you have delayed options set.
  • failed - Number of notifications that could not be delivered due to an error. You can find more information by viewing the notification in the dashboard.
  • converted - Number of users who have clicked / tapped on your notification.

Result Format - View notification

{
  "id":"481a2734-6b7d-11e4-a6ea-4b53294fa671",
  "successful":15,
  "failed":1,
  "converted":3,
  "remaining":0,
  "queued_at":1415914655,
  "send_after":1415914655,  
  "url": "https://yourWebsiteToOpen.com",
  "data":{
    "foo":"bar",
   	"your":"custom metadata"
  },
  "canceled": false,
  "headings":{
      "en":"English and default langauge heading",
      "es":"Spanish language heading"
  },
  "contents":{
    "en":"English language content",
    "es":"Hola"
  }
}

View notifications

View the details of multiple notifications

 
gethttps://onesignal.com/api/v1/notifications?app_id=:app_id&limit=:limit&offset=:offset
 

Requires Authentication Key

Requires your OneSignal App Auth Key, available in Keys & IDs.

OneSignal periodically deletes records of API notifications older than 30 days.

Path Parameters

Parameter
Type
Description

app_id

String

Required The app ID that you want to view notifications from

limit

String

How many notifications to return. Max is 50. Default is 50

offset

String

Result offset. Default is 0. Results are sorted by queued_at in descending order. queued_at is the unixtime representation of the time that the notification was queued.

Example Code - View notifications

curl --include \
     --header "Authorization: Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" \
     https://onesignal.com/api/v1/notifications?app_id={appId}
<?PHP
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://onesignal.com/api/v1/notifications?app_id=3cb5beaa-e6ca-5932-aad9-fdabaa3b83ce&limit=50&offset=0",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "authorization: Basic ONESIGNAL_APP_REST_API_KEY_HERE",
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

echo $response;
?>

Result Format - View notifications

{
 "total_count":3,
 "offset":2,
 "limit":2,
 "notifications":
 [
   {
    "id":"481a2734-6b7d-11e4-a6ea-4b53294fa671",
    "successful":15,
    "failed":1,
    "converted":3,
    "remaining":0,
    "queued_at":1415914655,
    "send_after":1415914655,
    "canceled": false,
    "url": "https://yourWebsiteToOpen.com",
    "data":null,
		"headings":{
      "en":"English and default langauge heading",
      "es":"Spanish language heading"
    },     
    "contents":{
      "en":"English and default content",
      "es":"Hola"
    }
   },
   {
    "id":"b6b326a8-40aa-13e5-b91b-bf8bc3fa26f7",
    "successful":5,
    "failed":2,
    "converted":0,
    "remaining":0,
    "queued_at":1415915123,
    "send_after":1415915123,
    "canceled": false,
    "url": nil,
    "data":{
      "foo":"bar",
      "your":"custom metadata"
    },
    "headings":{
      "en":"English and default langauge heading",
      "es":"Spanish language heading"
    },
    "contents":{
      "en":"English and default content",
      "es":"Hola"
    }
   }
 ]
}

Track open

Track when users open a notification

 
puthttps://onesignal.com/api/v1/notifications/:id
 

Path Parameters

Parameter
Type
Description

id

String

Required Notification id

Body Parameters

Parameter
Type
Description

app_id

String

Required OneSignal app id, available in Keys & IDs

opened

boolean

Required Set to true

Example Code - Track open

curl --include \
     --request PUT \
     --header "Content-Type: application/json" \
     --data-binary "{\"opened\":true, \"app_id\":"YOUR APP ID"}" \
     https://onesignal.com/api/v1/notifications/{notificationId}

Result Format - Track open

{"success": true}
{}