> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.onesignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Create segment

> Programmatically create segments in your OneSignal app using flexible filters and targeting rules.

## Overview

Use this API to create new [Segments](/docs/en/segmentation) programmatically. These segments are then accessible in the OneSignal Dashboard and usable in messages, Journeys, and in-app messaging campaigns.

<Note>
  To modify an existing segment, use the [Update segment](/reference/update-segment) API.
</Note>

***

## 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](/reference/view-segments) and [View segment](/reference/view-segment) APIs.

```json theme={null}
{
  "name": "YOUR_SEGMENT_NAME",
  "description": "YOUR_SEGMENT_DESCRIPTION",
  "filters": [
    {"field": "session_count", "relation": ">", "value": "10"}
  ]
}
```

### Define the `filters`

Available filters:

* [operator](#operator)
* [tag](#tag)
* [last\_session](#last_session)
* [first\_session](#first_session)
* [session\_count](#session_count)
* [session\_time](#session_time-1)
* [language](#language)
* [app\_version](#app_version)
* [location](#location)
* [country](#country)

### `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.

<CodeGroup>
  ```json AND example theme={null}
  // 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"}
  ]

  ```

  ```json OR example theme={null}
  // 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"}
  ]
  ```

  ```json Combinations theme={null}
  // 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"}
    ]
  }
  ```
</CodeGroup>

### `tag`

**Description**

Target based on custom user [Tags](/docs/en/add-user-data-tags).

<Warning>
  Do not use tags for targeting individual users like a "user id".
  Instead use [External ID](/docs/en/users) or custom [Aliases](/docs/en/aliases) and the `include_aliases` targeting property.
</Warning>

* `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](/docs/en/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.

```json theme={null}
"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](/docs/en/subscriptions) 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"`

Last Session updates every time the app is opened in a new session, regardless of how long the user stays. A new session starts when the app is opened after being backgrounded for 30+ seconds, or on a fresh launch. Because any qualifying app open refreshes this value, `last_session` is the recommended filter for targeting recently active users (for example, "active in the last 3 months").

```json theme={null}
"filters": [
  {"field": "last_session", "relation": ">","hours_ago": "10"}
]
```

### `first_session`

**Description**

Time since the [User](/docs/en/users) 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"`

  ```json theme={null}
  "filters": [
    {"field": "first_session", "relation": "<","hours_ago": "24"}
  ]
  ```

### `session_count`

**Description**

Total number of sessions by the [Subscription](/docs/en/subscriptions).

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

  ```json theme={null}
  "filters": [
    {"field": "session_count", "relation": ">","value": "5"}
  ]
  ```

### `session_time`

**Description**

Total time the [Subscription](/docs/en/subscriptions) 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.

  ```json theme={null}
  "filters": [
    {"field": "session_time", "relation": ">","value": "86400"}
  ]
  ```

### `language`

**Description**

[User’s](/docs/en/users) language code (e.g., "en"). See [Multi-Language Messaging](/docs/en/multi-language-messaging) for details and [supported language codes](/docs/en/multi-language-messaging#supported-languages).

* `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.

  ```json theme={null}
  "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](/docs/en/subscriptions).

* `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.

  ```json theme={null}
  "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](/docs/en/location-triggered-event) for details.

* `radius` = in meters
* `lat` = latitude
* `long` = longitude

  ```json theme={null}
  "filters": [
    {"field": "location", "radius": "1000","lat": "37.77", "long":"-122.43"}
  ]
  ```

### `country`

**Description**

Country code of your [Users](/docs/en/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.

  ```json theme={null}
  "filters": [
    {"field": "country", "relation": "=", "value": "US"},
    {"operator": "OR"},
    {"field": "country", "relation": "in_array", "value": "MA,GB,LK"}
  ]
  ```

***


## OpenAPI

````yaml POST /apps/{app_id}/segments
openapi: 3.1.0
info:
  title: api.onesignal.com
  version: '11.6'
servers:
  - url: https://api.onesignal.com
security:
  - {}
paths:
  /apps/{app_id}/segments:
    post:
      summary: Create segment
      description: >-
        Programmatically create segments in your OneSignal app using flexible
        filters and targeting rules.
      operationId: create-segments
      parameters:
        - name: app_id
          in: path
          description: >-
            Your OneSignal App ID in UUID v4 format. See [Keys &
            IDs](/docs/en/keys-and-ids).
          schema:
            type: string
            default: YOUR_APP_ID
          required: true
        - name: Authorization
          in: header
          description: >-
            Your App API key with prefix `Key `. See [Keys &
            IDs](/docs/en/keys-and-ids).
          required: true
          schema:
            type: string
            default: Key YOUR_APP_API_KEY
        - name: Content-Type
          in: header
          required: true
          schema:
            type: string
            default: application/json; charset=utf-8
      requestBody:
        content:
          application/json:
            schema:
              type: object
              required:
                - name
                - filters
              properties:
                id:
                  type: string
                  description: >-
                    UUID of the segment. If left empty, it will be assigned
                    automatically.
                name:
                  type: string
                  description: >-
                    An internal name you set to help organize and track
                    Segments. Maximum 128 characters.
                  default: YOUR_SEGMENT_NAME
                description:
                  type: string
                  description: >-
                    Optional human-readable description for the segment. Maximum
                    255 characters.
                  maxLength: 255
                  default: YOUR_SEGMENT_DESCRIPTION
                filters:
                  type: array
                  description: >-
                    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](/reference/create-message#filters).
                  items:
                    oneOf:
                      - title: Filter
                        description: Required. The fitler object.
                        required:
                          - field
                          - relation
                        type: object
                        properties:
                          field:
                            type: string
                            description: The name of the filter to use.
                            enum:
                              - tag
                              - last_session
                              - first_session
                              - session_count
                              - session_time
                              - language
                              - app_version
                              - location
                              - country
                          relation:
                            type: string
                            description: >-
                              Used with most filters. See details on the
                              specific filter.
                            enum:
                              - '='
                              - '!='
                              - '>'
                              - <
                              - exists
                              - not_exists
                              - in_array
                              - not_in_array
                              - time_elapsed_gt
                              - time_elapsed_lt
                          key:
                            type: string
                            description: Used with the `tag` filter. This is the tag `key`.
                          value:
                            type: string
                            description: >-
                              The value of the `field` or tag `key` in which you
                              want to filter with.
                      - title: Operator
                        type: object
                        properties:
                          operator:
                            type: string
                            description: >-
                              Chain filter conditions with implicit `AND` and
                              `OR` logic. Never end your `filters` object with
                              an `operator`. See
                              [filters](/reference/create-message#filters) for
                              more.
                            enum:
                              - AND
                              - OR
                            default: AND
                  minItems: 1
                  maxItems: 200
      responses:
        '201':
          description: '201'
          content:
            application/json:
              examples:
                Result:
                  value:
                    success: true
                    id: 7ed2887d-bd24-4a81-8220-4b256a08ab19
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    description: >-
                      true if the segment was created successfully, false
                      otherwise.
                    default: true
                  id:
                    type: string
                    description: The UUID of the created segment.
        '400':
          description: '400'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BasicErrorResponse'
              example:
                errors:
                  - The reason why the segment was not created.
        '403':
          description: >-
            Forbidden. Your app's plan does not allow this segment operation, or
            the Authorization key does not have permission.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BasicErrorResponse'
              example:
                errors:
                  - This API is not available for applications on your plan.
        '422':
          description: >-
            Unprocessable Entity. The segment cannot be created because the app
            has reached an entitlement limit on segments (e.g., the maximum
            number of segments allowed for this plan). Distinct from 403 (which
            signals a permission denial); 422 is specifically a plan-limits
            failure.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BasicErrorResponse'
              example:
                errors:
                  - >-
                    You have reached the maximum number of segments allowed for
                    your plan.
        '429':
          description: >-
            Rate limit exceeded. Wait the number of seconds in the `Retry-After`
            header before retrying.
          headers:
            Retry-After:
              description: >-
                Number of seconds to wait before retrying the request. Always
                emitted on 429 responses.
              schema:
                type: integer
                minimum: 0
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BasicErrorResponse'
              example:
                errors:
                  - API rate limit exceeded
        '503':
          description: >-
            Service temporarily unavailable. Retry after a short backoff. The
            body may be empty or non-JSON in some failure modes.
          headers:
            Retry-After:
              description: >-
                Number of seconds to wait before retrying. Optional — may be
                absent when the response is generated upstream.
              schema:
                type: integer
                minimum: 0
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BasicErrorResponse'
              example:
                errors:
                  - Service temporarily unavailable
      deprecated: false
      security: []
      x-codeSamples:
        - lang: typescript
          label: Node.js SDK
          source: >-
            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;
              }
            }
        - lang: python
          label: Python SDK
          source: >-
            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)
        - lang: php
          label: PHP SDK
          source: >-
            <?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;
            }
        - lang: go
          label: Go SDK
          source: |-
            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)
            }
        - lang: ruby
          label: Ruby SDK
          source: >-
            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
        - lang: java
          label: Java SDK
          source: |-
            // 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();
                }
              }
            }
        - lang: csharp
          label: C# SDK
          source: |-
            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);
                        }
                    }
                }
            }
        - lang: rust
          label: Rust SDK
          source: |-
            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),
                }
            }
components:
  schemas:
    BasicErrorResponse:
      type: object
      properties:
        errors:
          type: array
          items:
            type: string
          description: One or more human-readable error messages.
        success:
          type: boolean
          description: >-
            Present (and `false`) on some endpoints (notifications, templates,
            segments). Not emitted by every endpoint.
        reference:
          type: array
          items:
            type: string
          description: >-
            Documentation URL fragments related to the error. Only emitted by
            the API-key auth error helpers.

````