# Segments

Segments are portions of your audience that have arbitrary metadata (e.g., tags, location data, etc.) attached. You can create, delete, update, or request information on a Segment via the `/api/segments/` endpoint. Pushing to a Segment is done through the `/api/push/` endpoint. See the [Audience selection](/developer/rest-api/ua/schemas/audience-selection/) section for more information.


## Create Segment {#createsegment}

Create a new Segment.

[Jump to examples ↓](#createsegment-examples)

### `POST /api/segments`

**Security:**

- [basicAuth]({{< ref "/developer/rest-api/ua/introduction/" >}}#security-basicAuth)
- [bearerAuth]({{< ref "/developer/rest-api/ua/introduction/" >}}#security-bearerAuth)

**Request body**

A single Segment object.

**Content-Type:** `application/json`

- **`criteria`** `object` **REQUIRED**

  Defines the set of devices to send notifications to. `criteria` is a JSON expression containing the same information as the audience selector, including [Event Segmentation](/docs/developer/rest-api/ua/schemas/event-segmentation/). See [Audience selection](/docs/developer/rest-api/ua/schemas/audience-selection/) for more information.

  **One of:**

  - [Compound selector]({{< ref "/developer/rest-api/ua/schemas/audience-selection/" >}}#compoundselector)

    Compound selectors combine boolean operators (AND, OR, or NOT) with atomic or nested compound selectors.

  - [Atomic selector]({{< ref "/developer/rest-api/ua/schemas/audience-selection/" >}}#atomicselector)

    Atomic selectors are the simplest way to identify a single device, i.e., app or browser installation, or a group of devices. These selectors are either a unique identifier for the device such as a Channel ID or metadata that maps to the device (or multiple devices) such as a tag.


- **`display_name`** `string` **REQUIRED**

  Human readable name for this Segment. This will be used in the dashboard.

  Example: `News but not sports`

**Responses**

**`201`** The Segment was created.

Response headers:

| Name | Type | Description |
|------|------|-------------|
| `Location` | `string` | The newly created Segment. |

Response body:

**Content-Type:** `application/vnd.urbanairship+json; version=3`

- **`ok`** `boolean`

  If true, the operation completed successfully and returns expected results.

- **`operation_id`** `string`

  A unique string identifying an API call, and can be used to identify operations in reporting and troubleshooting logs.

  Format: `uuid`

  Example: `ef625038-70a3-41f1-826f-57bc11dd625a`

- **`segment_id`** `string`

  The ID of the newly created Segment.

  Format: `uuid`

  Example: `1d154121-951f-45b9-896d-e70718b5865b`

**`400`** There was a parsing or validation error in the request. Bad Request errors typically include `path` and `location` in the response to help you find the cause of the error.

Response body:

**Content-Type:** `application/json`

[Error response]({{< ref "/developer/rest-api/ua/schemas/responses/" >}}#error)

**`401`** Authentication information (the app key and secret or bearer token) was either incorrect or missing.

Response body:

**Content-Type:** `text/plain`

[Error response]({{< ref "/developer/rest-api/ua/schemas/responses/" >}}#error)

**Examples**

*Example*

```http
POST /api/segments HTTP/1.1
Authorization: Basic <master authorization string>
Accept: application/vnd.urbanairship+json; version=3
Content-Type: application/json

{
   "display_name": "News but not sports",
   "criteria": {
      "and": [
         {"tag": "news"},
         {"not":
            {"tag": "sports"}
         }
      ]
   }
}

```

```http
HTTP/1.1 201 Created
Location: https://go.urbanairship.com/api/segments/f35da41d-59c1-4106-a192-9594bd480cb6
Content-Type: application/vnd.urbanairship+json; version=3

{
   "ok": true,
   "segment_id": "f35da41d-59c1-4106-a192-9594bd480cb6",
   "operation_id": "1d154121-951f-45b9-896d-e70718b5865b"
}

```

```java
UrbanAirshipClient client = UrbanAirshipClient.newBuilder()
        .setKey("<app key>")
        .setSecret("<master secret>")
        .build();

// Define the segment criteria
Selector compound = Selectors.and(Selectors.tag("news"), Selectors.not(Selectors.tag("sports")));

SegmentRequest request = SegmentRequest.newRequest();
request.setCriteria(compound);
request.setDisplayName("News but not sports");

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

```

```python
from urbanairship import (
    BasicAuthClient, Segment,
    tag, not_, and_
)

client = BasicAuthClient(
    key='<app_key>',
    secret='<master_secret>'
)

# Create a new segment
segment = Segment()
segment.display_name = "News but not sports"
segment.criteria = and_(
    tag('news'),
    not_(tag('sports'))
)

# Create the segment
response = segment.create(client)

```

```ruby
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: '<app key>', secret: '<master secret>')

segment = UA::Segment.new(client: airship)
segment.display_name = 'Display Name'
segment.criteria = { 'tag' => 'existing_tag' }
segment.create

```

---

## Delete Segment {#deletesegment}

Remove the Segment.

[Jump to examples ↓](#deletesegment-examples)

### `DELETE /api/segments/{segment_id}`

**Security:**

- [basicAuth]({{< ref "/developer/rest-api/ua/introduction/" >}}#security-basicAuth)
- [bearerAuth]({{< ref "/developer/rest-api/ua/introduction/" >}}#security-bearerAuth)

**Path parameters:**

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `segment_id` | `string` | Required | The Segment you want to retrieve. |

**Responses**

**`204`** An API request was successful, but there is no response body to return.

**`401`** Authentication information (the app key and secret or bearer token) was either incorrect or missing.

Response body:

**Content-Type:** `text/plain`

[Error response]({{< ref "/developer/rest-api/ua/schemas/responses/" >}}#error)

**`404`** The requested resource doesn't exist.

Response body:

**Content-Type:** `application/vnd.urbanairship+json`

[Error response]({{< ref "/developer/rest-api/ua/schemas/responses/" >}}#error)

**Examples**

*Example*

```http
DELETE /api/segments/00c0d899-a595-4c66-9071-bc59374bbe6b HTTP/1.1
Authorization: Basic <master authorization string>
Accept: application/vnd.urbanairship+json; version=3

```

```http
HTTP/1.1 204 No Content

```

```java
UrbanAirshipClient client = UrbanAirshipClient.newBuilder()
        .setKey("<app key>")
        .setSecret("<master secret>")
        .build();

SegmentDeleteRequest request = SegmentDeleteRequest.newRequest("00c0d899-a595-4c66-9071-bc59374bbe6b");
Response<GenericResponse> response = client.execute(request);

```

```python
from urbanairship import (
    BasicAuthClient, Segment
)

client = BasicAuthClient(
    key='<app_key>',
    secret='<master_secret>'
)

# Delete a segment
segment = Segment()
segment.from_id(client, "00c0d899-a595-4c66-9071-bc59374bbe6b")
response = segment.delete(client)

```

```ruby
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: '<app key>', secret: '<master secret>')

segment = UA::Segment.new(client: airship)
segment.from_id(id: '00c0d899-a595-4c66-9071-bc59374bbe6b')
segment.delete

```

---

## Segment listing {#getsegments}

List all segments for the application.

[Jump to examples ↓](#getsegments-examples)

### `GET /api/segments`

**Security:**

- [basicAuth]({{< ref "/developer/rest-api/ua/introduction/" >}}#security-basicAuth)
- [bearerAuth]({{< ref "/developer/rest-api/ua/introduction/" >}}#security-bearerAuth)

**Query parameters:**

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `limit` | `integer` |  | Set the limit to 200 or fewer Segment objects per request. Max: 200 |

**Responses**

**`200`** Returned on success a JSON object containing segments.

Response headers:

| Name | Type | Description |
|------|------|-------------|
| `Link` | `string` | A link to the next page of results. If present, follow this URL to the next page of segments. Also available in the `next_page` value in the response body. |

Response body:

**Content-Type:** `application/json`

- **`next_page`** `string`

  An optional relative URL which can be used to retrieve the next page of results. If no more results are available, next_page will be absent.

- **`segments`** `array[object]` **REQUIRED**

  An array of segments for the application.

**`401`** Authentication information (the app key and secret or bearer token) was either incorrect or missing.

Response body:

**Content-Type:** `text/plain`

[Error response]({{< ref "/developer/rest-api/ua/schemas/responses/" >}}#error)

**Examples**

*Example*

```http
GET /api/segments/ HTTP/1.1
Authorization: Basic <master authorization string>
Accept: application/vnd.urbanairship+json; version=3

```

```http
HTTP/1.1 200 OK
Link: <https://go.urbanairship.com/api/segments?limit=1&sort=id&order=asc&start=3832cf72-cb44-4132-a11f-eafb41b82f64>;rel=next
Content-Type: application/vnd.urbanairship+json; version=3

{
   "next_page": "https://go.urbanairship.com/api/segments?limit=1&sort=id&order=asc&start=3832cf72-cb44-4132-a11f-eafb41b82f64",
   "segments": [
      {
         "creation_date": 1346248822221,
         "display_name": "A segment",
         "id": "00c0d899-a595-4c66-9071-bc59374bbe6b",
         "modification_date": 1346248822221
      }
   ]
}

```

```java
UrbanAirshipClient client = UrbanAirshipClient.newBuilder()
        .setKey("<app key>")
        .setSecret("<master secret>")
        .build();

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

// Get the first segment in the list
SegmentListingView segment = response.getBody().get().getSegmentListingViews().get(0);

// Get the segment display name
String displayName = segment.getDisplayName();

// Get the segment ID
String id = segment.getSegmentId();

```

```python
from urbanairship import (
    BasicAuthClient, SegmentList
)

client = BasicAuthClient(
    key='<app_key>',
    secret='<master_secret>'
)

# List all segments
segment_list = SegmentList(client)
for segment in segment_list:
    print(segment.display_name)

```

```ruby
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: '<app key>', secret: '<master secret>')

segment_list = UA::SegmentList.new(client: airship)

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

```

---

## Segment lookup {#getsegment}

Lookup a Segment.

[Jump to examples ↓](#getsegment-examples)

### `GET /api/segments/{segment_id}`

**Security:**

- [basicAuth]({{< ref "/developer/rest-api/ua/introduction/" >}}#security-basicAuth)
- [bearerAuth]({{< ref "/developer/rest-api/ua/introduction/" >}}#security-bearerAuth)

**Path parameters:**

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `segment_id` | `string` | Required | The Segment you want to retrieve. |

**Responses**

**`200`** Returns OK for success.

Response body:

**Content-Type:** `application/json`

- **`criteria`** `object` **REQUIRED**

  Defines the set of devices to send notifications to. `criteria` is a JSON expression containing the same information as the audience selector, including [Event Segmentation](/docs/developer/rest-api/ua/schemas/event-segmentation/). See [Audience selection](/docs/developer/rest-api/ua/schemas/audience-selection/) for more information.

  **One of:**

  - [Compound selector]({{< ref "/developer/rest-api/ua/schemas/audience-selection/" >}}#compoundselector)

    Compound selectors combine boolean operators (AND, OR, or NOT) with atomic or nested compound selectors.

  - [Atomic selector]({{< ref "/developer/rest-api/ua/schemas/audience-selection/" >}}#atomicselector)

    Atomic selectors are the simplest way to identify a single device, i.e., app or browser installation, or a group of devices. These selectors are either a unique identifier for the device such as a Channel ID or metadata that maps to the device (or multiple devices) such as a tag.


- **`display_name`** `string` **REQUIRED**

  Human readable name for this Segment. This will be used in the dashboard.

  Example: `News but not sports`

**`401`** Authentication information (the app key and secret or bearer token) was either incorrect or missing.

Response body:

**Content-Type:** `text/plain`

[Error response]({{< ref "/developer/rest-api/ua/schemas/responses/" >}}#error)

**`404`** The requested resource doesn't exist.

Response body:

**Content-Type:** `application/vnd.urbanairship+json`

[Error response]({{< ref "/developer/rest-api/ua/schemas/responses/" >}}#error)

**Examples**

*Example*

```http
GET /api/segments/00c0d899-a595-4c66-9071-bc59374bbe6b HTTP/1.1
Authorization: Basic <master authorization string>
Accept: application/vnd.urbanairship+json; version=3

```

```http
HTTP/1.1 200 OK
Content-Type: application/vnd.urbanairship+json; version=3

{
   "criteria": {
      "and": [
         {
            "tag": "ipad"
         },
         {
            "not": {
               "tag": "foo"
            }
         }
      ]
   },
   "display_name": "A segment"
}

```

```java
UrbanAirshipClient client = UrbanAirshipClient.newBuilder()
        .setKey("<app key>")
        .setSecret("<master secret>")
        .build();

SegmentLookupRequest request = SegmentLookupRequest.newRequest("00c0d899-a595-4c66-9071-bc59374bbe6b");
Response<SegmentView> response = client.execute(request);

// Get the segment criteria
Selector criteria = response.getBody().get().getCriteria();

// Get the segment display name
String displayName = response.getBody().get().getDisplayName();

```

```python
from urbanairship import (
    BasicAuthClient, Segment
)

client = BasicAuthClient(
    key='<app_key>',
    secret='<master_secret>'
)

# Look up a segment by ID
segment = Segment()
response = segment.from_id(client, "00c0d899-a595-4c66-9071-bc59374bbe6b")

```

```ruby
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: '<app key>', secret: '<master secret>')

segment = UA::Segment.new(client: airship)
details = segment.from_id(id: '00c0d899-a595-4c66-9071-bc59374bbe6b')

```

---

## Update Segment {#updatesegment}

Change the definition of the Segment.

[Jump to examples ↓](#updatesegment-examples)

### `PUT /api/segments/{segment_id}`

{{< note >}}
Segmentation data is evaluated at send time. If you schedule a message that targets a Segment and then edit that Segment, the scheduled message automatically uses the updated Segment criteria. "Scheduled" includes recurring messages.
{{< /note >}}

**Security:**

- [basicAuth]({{< ref "/developer/rest-api/ua/introduction/" >}}#security-basicAuth)
- [bearerAuth]({{< ref "/developer/rest-api/ua/introduction/" >}}#security-bearerAuth)

**Path parameters:**

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `segment_id` | `string` | Required | The Segment you want to retrieve. |

**Request body**

A single Segment object.

**Content-Type:** `application/json`

- **`criteria`** `object` **REQUIRED**

  Defines the set of devices to send notifications to. `criteria` is a JSON expression containing the same information as the audience selector, including [Event Segmentation](/docs/developer/rest-api/ua/schemas/event-segmentation/). See [Audience selection](/docs/developer/rest-api/ua/schemas/audience-selection/) for more information.

  **One of:**

  - [Compound selector]({{< ref "/developer/rest-api/ua/schemas/audience-selection/" >}}#compoundselector)

    Compound selectors combine boolean operators (AND, OR, or NOT) with atomic or nested compound selectors.

  - [Atomic selector]({{< ref "/developer/rest-api/ua/schemas/audience-selection/" >}}#atomicselector)

    Atomic selectors are the simplest way to identify a single device, i.e., app or browser installation, or a group of devices. These selectors are either a unique identifier for the device such as a Channel ID or metadata that maps to the device (or multiple devices) such as a tag.


- **`display_name`** `string` **REQUIRED**

  Human readable name for this Segment. This will be used in the dashboard.

  Example: `News but not sports`

**Responses**

**`200`** Returned if the Segment has been successfully updated.

Response body:

**Content-Type:** `application/vnd.urbanairship+json; version=3`

[OK response]({{< ref "/developer/rest-api/ua/schemas/responses/" >}}#okresponseobject)

**`400`** There was a parsing or validation error in the request. Bad Request errors typically include `path` and `location` in the response to help you find the cause of the error.

Response body:

**Content-Type:** `application/json`

[Error response]({{< ref "/developer/rest-api/ua/schemas/responses/" >}}#error)

**`401`** Authentication information (the app key and secret or bearer token) was either incorrect or missing.

Response body:

**Content-Type:** `text/plain`

[Error response]({{< ref "/developer/rest-api/ua/schemas/responses/" >}}#error)

**`404`** The requested resource doesn't exist.

Response body:

**Content-Type:** `application/vnd.urbanairship+json`

[Error response]({{< ref "/developer/rest-api/ua/schemas/responses/" >}}#error)

**Examples**

*Example*

```http
PUT /api/segments/00c0d899-a595-4c66-9071-bc59374bbe6b HTTP/1.1
Authorization: Basic <master authorization string>
Accept: application/vnd.urbanairship+json; version=3
Content-Type: application/json

{
   "display_name": "Entertainment but not sports",
   "criteria": {
      "and": [
         {"tag": "entertainment"},
         {"not":
            {"tag": "sports"}
         }
      ]
   }
}

```

```http
HTTP/1.1 200 OK
Content-Length: 65
Content-Type: application/vnd.urbanairship+json;version=3

{
   "ok": true,
   "operation_id": "1f93ca85-b8fd-4833-8d1a-6e2b7f4ceea9"
}

```

```java
UrbanAirshipClient client = UrbanAirshipClient.newBuilder()
        .setKey("<app key>")
        .setSecret("<master secret>")
        .build();

// Define the segment criteria
Selector compound = Selectors.and(Selectors.tag("entertainment"), Selectors.not(Selectors.tag("sports")));

SegmentRequest request = SegmentRequest.newUpdateRequest("00c0d899-a595-4c66-9071-bc59374bbe6b");
request.setCriteria(compound);
request.setDisplayName("Entertainment but not sports");

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

```

```python
from urbanairship import (
    BasicAuthClient, Segment,
    tag, not_, and_
)

client = BasicAuthClient(
    key='<app_key>',
    secret='<master_secret>'
)

# Update an existing segment
segment = Segment()
segment.from_id(client, "00c0d899-a595-4c66-9071-bc59374bbe6b")

# Update segment properties
segment.display_name = "Entertainment but not sports"
segment.criteria = and_(
    tag('entertainment'),
    not_(tag('sports'))
)

# Save the changes
response = segment.update(client)

```

```ruby
require 'urbanairship'

UA = Urbanairship
airship = UA::Client.new(key: '<app key>', secret: '<master secret>')

segment = UA::Segment.new(client: airship)
segment.from_id(id: '00c0d899-a595-4c66-9071-bc59374bbe6b')
segment.display_name = 'New Display Name'
segment.criteria = { 'tag' => 'new_tag' }
segment.update

```

---

