Skip to main content
POST
/
apps
/
{app_id}
/
segments
cURL
curl --request POST \
  --url https://api.onesignal.com/apps/{app_id}/segments \
  --header 'Authorization: <authorization>' \
  --header 'Content-Type: <content-type>' \
  --data '
{
  "name": "YOUR_SEGMENT_NAME",
  "filters": [
    {
      "key": "<string>",
      "value": "<string>"
    }
  ],
  "id": "<string>",
  "description": "YOUR_SEGMENT_DESCRIPTION"
}
'
import Onesignal from '@onesignal/node-onesignal';

const configuration = Onesignal.createConfiguration({
restApiKey: 'YOUR_REST_API_KEY',
});
const apiInstance = new Onesignal.DefaultApi(configuration);

// string | The OneSignal App ID for your app. Available in Keys & IDs.
const appId: string = "00000000-0000-0000-0000-000000000000";
// Segment (optional)
const segment: Onesignal.Segment = {
id: "id_example",
name: "name_example",
filters: [
{
field: "field_example",
key: "key_example",
value: "value_example",
hours_ago: "hours_ago_example",
radius: 3.14,
lat: 3.14,
long: 3.14,
relation: ">",
},
],
};

try {
const response = await apiInstance.createSegment(appId, segment);
console.log(response);
} catch (e) {
if (e instanceof Onesignal.ApiException) {
// `e.errorMessages` flattens any error-envelope shape to a `string[]`;
// the raw parsed body remains on `e.body`.
console.error("createSegment failed: HTTP " + e.code, e.errorMessages);
} else {
throw e;
}
}
import onesignal
from onesignal.api import default_api
from onesignal.models import *
from pprint import pprint

# See configuration.py for a list of all supported configuration parameters.
# Some of the OneSignal endpoints require ORGANIZATION_API_KEY token for authorization, while others require REST_API_KEY.
# We recommend adding both of them in the configuration page so that you will not need to figure it out yourself.
configuration = onesignal.Configuration(
rest_api_key = "YOUR_REST_API_KEY", # App REST API key required for most endpoints
organization_api_key = "YOUR_ORGANIZATION_API_KEY" # Organization key is only required for creating new apps and other top-level endpoints
)


# Enter a context with an instance of the API client
with onesignal.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = default_api.DefaultApi(api_client)
app_id = "00000000-0000-0000-0000-000000000000" # The OneSignal App ID for your app. Available in Keys & IDs.
segment = Segment(
id="id_example",
name="name_example",
filters=[
Filter(
field="field_example",
key="key_example",
value="value_example",
hours_ago="hours_ago_example",
radius=3.14,
lat=3.14,
long=3.14,
relation=">",
),
],
)

try:
# Create Segment
api_response = api_instance.create_segment(app_id, segment=segment)
pprint(api_response)
except onesignal.ApiException as e:
print("Exception when calling DefaultApi->create_segment: %s\n" % e)
print("Status Code: %s" % e.status)
print("Response Body: %s" % e.body)
<?php
require_once(__DIR__ . '/vendor/autoload.php');


// Configure Bearer authorization: rest_api_key
$config = onesignal\client\Configuration::getDefaultConfiguration()
->setRestApiKeyToken('YOUR_REST_API_KEY')
->setOrganizationApiKeyToken('YOUR_ORGANIZATION_API_KEY');



$apiInstance = new onesignal\client\Api\DefaultApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client(),
$config
);
$app_id = '00000000-0000-0000-0000-000000000000'; // string | The OneSignal App ID for your app. Available in Keys & IDs.
$segment = new \onesignal\client\model\Segment(); // \onesignal\client\model\Segment

try {
$result = $apiInstance->createSegment($app_id, $segment);
print_r($result);
} catch (\onesignal\client\ApiException $e) {
echo 'Exception when calling DefaultApi->createSegment: ', $e->getMessage(), PHP_EOL;
echo 'Status Code: ', $e->getCode(), PHP_EOL;
// getErrorMessages() flattens any error-envelope shape to a string[];
// the raw body remains on getResponseBody().
echo 'Error Messages: ', implode(', ', $e->getErrorMessages()), PHP_EOL;
echo 'Response Body: ', $e->getResponseBody(), PHP_EOL;
} catch (\Exception $e) {
echo 'Exception when calling DefaultApi->createSegment: ', $e->getMessage(), PHP_EOL;
}
package main

import (
"context"
"fmt"
"os"

"github.com/OneSignal/onesignal-go-api/v5"
)

func main() {
appId := "00000000-0000-0000-0000-000000000000" // string | The OneSignal App ID for your app. Available in Keys & IDs.
segment := *onesignal.NewSegment("Name_example", []onesignal.FilterExpression{onesignal.FilterExpression{Filter: onesignal.NewFilter()}}) // Segment | (optional)

configuration := onesignal.NewConfiguration()
apiClient := onesignal.NewAPIClient(configuration)

restAuth := context.WithValue(context.Background(), onesignal.RestApiKey, "YOUR_REST_API_KEY") // App REST API key required for most endpoints

resp, r, err := apiClient.DefaultApi.CreateSegment(restAuth, appId).Segment(segment).Execute()

if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `DefaultApi.CreateSegment``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
if apiErr, ok := err.(*onesignal.GenericOpenAPIError); ok {
// ErrorMessages() flattens any error-envelope shape to a []string;
// the raw body remains on Body().
fmt.Fprintf(os.Stderr, "Error Messages: %v\n", apiErr.ErrorMessages())
fmt.Fprintf(os.Stderr, "Response Body: %s\n", apiErr.Body())
}
}
// response from `CreateSegment`: CreateSegmentSuccessResponse
fmt.Fprintf(os.Stdout, "Response from `DefaultApi.CreateSegment`: %v\n", resp)
}
require 'onesignal'
# setup authorization
OneSignal.configure do |config|
# Configure Bearer authorization: rest_api_key
config.rest_api_key = 'YOUR_REST_API_KEY'

end

api_instance = OneSignal::DefaultApi.new
app_id = '00000000-0000-0000-0000-000000000000' # String | The OneSignal App ID for your app. Available in Keys & IDs.
opts = {
segment: OneSignal::Segment.new({name: 'name_example', filters: [OneSignal::Filter.new]}) # Segment |
}

begin
# Create Segment
result = api_instance.create_segment(app_id, opts)
p result
rescue OneSignal::ApiError => e
puts "Error when calling DefaultApi->create_segment: #{e}"
puts "Status Code: #{e.code}"
# `e.error_messages` flattens any error-envelope shape to an Array<String>;
# the raw body remains on `e.response_body`.
puts "Error Messages: #{e.error_messages}"
puts "Response Body: #{e.response_body}"
end
// Import classes:
import com.onesignal.client.ApiClient;
import com.onesignal.client.ApiException;
import com.onesignal.client.Configuration;
import com.onesignal.client.auth.*;
import com.onesignal.client.model.*;
import com.onesignal.client.api.DefaultApi;

public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://api.onesignal.com");

// Configure HTTP bearer authorization: rest_api_key
HttpBearerAuth rest_api_key = (HttpBearerAuth) defaultClient.getAuthentication("rest_api_key");
rest_api_key.setBearerToken("YOUR_REST_API_KEY");

DefaultApi apiInstance = new DefaultApi(defaultClient);
String appId = "00000000-0000-0000-0000-000000000000"; // String | The OneSignal App ID for your app. Available in Keys & IDs.
Segment segment = new Segment(); // Segment |
try {
CreateSegmentSuccessResponse result = apiInstance.createSegment(appId, segment);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DefaultApi#createSegment");
System.err.println("Status code: " + e.getCode());
// getErrorMessages() flattens any error-envelope shape to a List<String>;
// the raw body remains on getResponseBody().
System.err.println("Error messages: " + e.getErrorMessages());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using OneSignalApi.Api;
using OneSignalApi.Client;
using OneSignalApi.Model;

namespace Example
{
public class CreateSegmentExample
{
public static void Main()
{
Configuration config = new Configuration();
config.BasePath = "https://api.onesignal.com";
// Configure Bearer token for authorization: rest_api_key
config.AccessToken = "YOUR_REST_API_KEY";

var apiInstance = new DefaultApi(config);
var appId = "00000000-0000-0000-0000-000000000000"; // string | The OneSignal App ID for your app. Available in Keys & IDs.
var segment = new Segment(); // Segment | (optional)

try
{
// Create Segment
CreateSegmentSuccessResponse result = apiInstance.CreateSegment(appId, segment);
Debug.WriteLine(result);
}
catch (ApiException e)
{
Debug.Print("Exception when calling DefaultApi.CreateSegment: " + e.Message );
Debug.Print("Status Code: "+ e.ErrorCode);
// e.ErrorMessages flattens any error-envelope shape to an IReadOnlyList<string>;
// the raw body remains on e.ErrorContent.
Debug.Print("Error Messages: " + string.Join(", ", e.ErrorMessages));
Debug.Print("Response Body: " + e.ErrorContent);
Debug.Print(e.StackTrace);
}
}
}
}
use onesignal_rust_api::apis::configuration::Configuration;
use onesignal_rust_api::apis::default_api;

use onesignal_rust_api::models;


#[tokio::main]
async fn main() {
let mut configuration = Configuration::new();
configuration.rest_api_key_token = Some("YOUR_REST_API_KEY".to_string());


// Realistic values are pulled from the spec's `example:` fields where present.
let app_id: &str = "00000000-0000-0000-0000-000000000000";
let segment: Option<models::Segment> = None;

match default_api::create_segment(&configuration, app_id, segment).await {
Ok(resp) => println!("{:?}", resp),
Err(e @ onesignal_rust_api::apis::Error::ResponseError(_)) => {
// `e.error_messages()` flattens any error-envelope shape to a Vec<String>;
// the raw response remains on the ResponseError variant.
eprintln!("create_segment failed: {:?}", e.error_messages());
}
Err(e) => eprintln!("create_segment failed: {:?}", e),
}
}
{
  "success": true,
  "id": "7ed2887d-bd24-4a81-8220-4b256a08ab19"
}
{
"errors": [
"The reason why the segment was not created."
]
}
{
"errors": [
"This API is not available for applications on your plan."
]
}
{
"errors": [
"You have reached the maximum number of segments allowed for your plan."
]
}
{
"errors": [
"API rate limit exceeded"
]
}
{
"errors": [
"Service temporarily unavailable"
]
}

Overview

Use this API to create new Segments programmatically. These segments are then accessible in the OneSignal Dashboard and usable in messages, Journeys, and in-app messaging campaigns.
To modify an existing segment, use the Update segment API.

How to use this API

This endpoint allows your backend to define audience segments by passing in a combination of filters and logical operators like "AND" and "OR", mirroring the segmentation capabilities of the OneSignal Dashboard.

Name the segment

The name of the segment as it shows in the OneSignal dashboard and accessible via the included_segments and excluded_segments targeting parameters.

Describe the segment

Optionally include a description (max 255 characters) to record the segment’s purpose. The description is returned by the View segments and View segment APIs.
{
  "name": "YOUR_SEGMENT_NAME",
  "description": "YOUR_SEGMENT_DESCRIPTION",
  "filters": [
    {"field": "session_count", "relation": ">", "value": "10"}
  ]
}

Define the filters

Available filters:

operator

Description Allows you to combine or separate properties. Filters combined with an "AND" have higher priority than "OR" filters.
  • "AND" = the 2+ connected filters must be satisfied for the recipient to be included. Filter entries use this by default and its not required to be included.
  • "OR" = the 2 filters separated by the "OR" operator are mutually exclusive. The recipients only need to satisfy the conditions on either side of the "OR" operator.
// Users must satisfy both filters to be included.
// Notice the AND operator is not required

"filters": [
{"field": "tag", "key": "level", "relation": "=", "value": "10"},
{"field": "language", "relation": "=","value": "en"}
]

// The same example using the AND operator. This is not required.
"filters": [
{"field": "tag", "key": "level", "relation": "=", "value": "10"},
{"operator": "AND"},
{"field": "language", "relation": "=","value": "en"}
]

// Users can satisfy either filter to be included.

"filters": [
  {"field": "tag", "key": "level", "relation": "=", "value": "10"},
  {"operator": "OR"},
  {"field": "tag", "key": "level", "relation": "=", "value": "20"}
]
// In this example, users must either have:
// The specified session_count AND tag requirement
// Or it will be all records where last_session is satisfied
{
  "name": "2 filters or 1",
  "filters": [
    {"field": "session_count", "relation": ">", "value": "2"},
    {"operator": "AND"},
    {"field": "tag", "relation": "!=", "key": "tag_key", "value": "1"},
    {"operator": "OR"},
    {"field": "last_session", "relation": "<", "hours_ago": "30"}
  ]
}

// Similar to the first example, this shows how to require a specific field
// across other filters

{
  "name": "3 filters, 1 required across all",
  "filters": [
    {"field": "session_count", "relation": ">", "value": "2"},
    {"operator": "AND"},
    {"field": "tag", "relation": "!=", "key": "tag_key", "value": "1"},
    {"operator": "OR"},
    {"field": "last_session", "relation": "<", "hours_ago": "30"},
    {"operator": "AND"},
    {"field": "tag", "relation": "!=", "key": "tag_key", "value": "1"}
  ]
}

tag

Description Target based on custom user Tags.
Do not use tags for targeting individual users like a “user id”. Instead use External ID or custom Aliases and the include_aliases targeting property.
  • relation = ">", "<", "=", "!=", "exists", "not_exists", "in_array", "not_in_array", "time_elapsed_gt", (time elapsed greater than) and "time_elapsed_lt" (time elapsed less than)
    • time_elapsed_gt/lt fields correspond to Time Operators and require a paid plan.
  • key = Tag key to compare.
  • value = Tag value to compare. Not required for "exists" or "not_exists". For "in_array" and "not_in_array", the value should be a comma-separated list of up to 20 values.
"filters": [
  {"field": "tag", "key": "level", "relation": "=", "value": "10"},
  {"operator": "OR"},
  {"field": "tag", "key": "level", "relation": "in_array", "value": "10,20,30"}
]

last_session

Description Time since the Subscription last used the app (in hours_ago).
  • relation = ">" or "<"
  • hours_ago = number of hours before or after the user’s last session. Example: "1.1"
    "filters": [
      {"field": "last_session", "relation": ">","hours_ago": "10"}
    ]
    

first_session

Description Time since the User first used the app or was created within OneSignal (in hours_ago).
  • relation = ">" or "<"
  • hours_ago = number of hours before or after the user’s first session. Example: "1.1"
    "filters": [
      {"field": "first_session", "relation": "<","hours_ago": "24"}
    ]
    

session_count

Description Total number of sessions by the Subscription.
  • relation = ">", "<", "=" or "!="
  • value = number of sessions. Example: "1"
    "filters": [
      {"field": "session_count", "relation": ">","value": "5"}
    ]
    

session_time

Description Total time the Subscription has spent in the app, in seconds.
  • relation = ">" or "<"
  • value = time in seconds the user has been in your app. Example: 1 day is "86400" seconds.
    "filters": [
      {"field": "session_time", "relation": ">","value": "86400"}
    ]
    

language

Description User’s language code (e.g., “en”). See Multi-Language Messaging for details and supported language codes.
  • relation = "=", "!=", "in_array", or "not_in_array"
  • value = 2 character language code. Example: "en". For "in_array" and "not_in_array", the value should be a comma-separated list of up to 20 values.
    "filters": [
      {"field": "language", "relation": "=","value": "en"},
      {"operator": "OR"},
      {"field": "language", "relation": "in_array","value": "es,fr,de"}
    ]
    

app_version

Description App version set on the Subscription.
  • relation = ">", "<", "=", "!=", "in_array", or "not_in_array"
  • value = app version. Example: "1.0.0" For "in_array" and "not_in_array", the value should be a comma-separated list of up to 20 values.
    "filters": [
      {"field": "app_version", "relation": "=","value": "1.0.1"},
      {"operator": "OR"},
      {"field": "app_version", "relation": "in_array","value": "1.0.0,1.0.1"}
    ]
    

location

Description Target by GPS coordinates and radius. Location tracking must be turned on and accepted by the user. See Location-Triggered Notifications for details.
  • radius = in meters
  • lat = latitude
  • long = longitude
    "filters": [
      {"field": "location", "radius": "1000","lat": "37.77", "long":"-122.43"}
    ]
    

country

Description Country code of your Users. Uses ISO 3166-1 Alpha-2 format (two-letter country code).
  • relation = "=", "!=", "in_array", or "not_in_array"
  • value = Two-letter country code in uppercase. Example: "US", "GB", "CA". For "in_array" and "not_in_array", the value should be a comma-separated list of up to 20 values.
    "filters": [
      {"field": "country", "relation": "=", "value": "US"},
      {"operator": "OR"},
      {"field": "country", "relation": "in_array", "value": "MA,GB,LK"}
    ]
    

Headers

Authorization
string
default:Key YOUR_APP_API_KEY
required

Your App API key with prefix Key. See Keys & IDs.

Content-Type
string
default:application/json; charset=utf-8
required

Path Parameters

app_id
string
default:YOUR_APP_ID
required

Your OneSignal App ID in UUID v4 format. See Keys & IDs.

Body

application/json
name
string
default:YOUR_SEGMENT_NAME
required

An internal name you set to help organize and track Segments. Maximum 128 characters.

filters
(Filter · object | Operator · object)[]
required

Filters define the segment based on user properties like tags, activity, or location using flexible AND/OR logic. Limited to 200 total entries, including fields and OR operators. See Sending messages with the OneSignal API.

Required array length: 1 - 200 elements

Required. The fitler object.

id
string

UUID of the segment. If left empty, it will be assigned automatically.

description
string
default:YOUR_SEGMENT_DESCRIPTION

Optional human-readable description for the segment. Maximum 255 characters.

Maximum string length: 255

Response

201

success
boolean
default:true

true if the segment was created successfully, false otherwise.

id
string

The UUID of the created segment.