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

# Update segment

> Update an existing segment's name and/or filters. The name parameter is always required. When filters are provided, all existing filters are replaced with the new ones.

## Overview

Update an existing segment's name and/or filters. This API allows you to modify [Segments](/docs/en/segmentation) programmatically without having to delete and recreate them.

<Note>
  The `name` parameter is always required, even if you're not changing it. When filters are provided, all existing filters are **replaced** with the new ones. Omit the `filters` parameter to keep existing filters intact. The `filters` array cannot be empty—if provided, it must contain at least one filter.
</Note>

***

## How to use this API

### Update segment name only

To update just the segment name without changing filters:

```json theme={null}
{
  "name": "New Segment Name"
}
```

### Update segment description

Update the optional `description` (max 255 characters). Pass an empty string to clear the existing description; omit the field to leave it unchanged.

```json theme={null}
{
  "name": "YOUR_SEGMENT_NAME",
  "description": "YOUR_SEGMENT_DESCRIPTION"
}
```

### Update segment filters

To update the segment filters (this replaces all existing filters), provide the `name` (required) and `filters`:

```json theme={null}
{
  "name": "Updated Segment",
  "filters": [
    {"field": "session_count", "relation": ">", "value": "5"},
    {"operator": "AND"},
    {"field": "tag", "key": "subscription", "relation": "=", "value": "premium"}
  ]
}
```

### Filter syntax

The filter syntax is identical to the [Create segment](/reference/create-segments) API. Available filters include:

* `tag` - Filter by Tags
* `last_session` - Filter by last active time
* `first_session` - Filter by first session time
* `session_count` - Filter by number of sessions
* `session_time` - Filter by total usage duration
* `language` - Filter by user language
* `app_version` - Filter by app version
* `location` - Filter by GPS coordinates
* `country` - Filter by country

Use `AND` and `OR` operators to combine filters:

```json theme={null}
{
  "name": "Engaged Premium Users",
  "filters": [
    {"field": "tag", "key": "plan", "relation": "=", "value": "premium"},
    {"operator": "AND"},
    {"field": "session_count", "relation": ">", "value": "10"},
    {"operator": "OR"},
    {"field": "tag", "key": "vip", "relation": "=", "value": "true"}
  ]
}
```

***

## Response

### Success response

```json theme={null}
{
  "success": true,
  "id": "7ed2887d-bd24-4a81-8220-4b256a08ab19"
}
```

### Error responses

| Status Code | Description                                                                              |
| ----------- | ---------------------------------------------------------------------------------------- |
| 400         | Bad request - Invalid filters, duplicate segment name, or segment used by active Journey |
| 403         | Forbidden - API not available for your plan                                              |
| 404         | Not found - Segment does not exist                                                       |
| 429         | Rate limit exceeded                                                                      |

***


## OpenAPI

````yaml PATCH /apps/{app_id}/segments/{segment_id}
openapi: 3.1.0
info:
  title: api.onesignal.com
  version: '11.6'
servers:
  - url: https://api.onesignal.com
security:
  - {}
paths:
  /apps/{app_id}/segments/{segment_id}:
    patch:
      summary: Update segment
      description: >-
        Update an existing segment's name and/or filters. The name parameter is
        always required. When filters are provided, all existing filters are
        replaced with the new ones.
      operationId: update-segment
      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: segment_id
          in: path
          description: >-
            The `segment_id` can be found in the URL of the segment when viewing
            it in the dashboard.
          schema:
            type: string
            default: YOUR_SEGMENT_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
              properties:
                name:
                  type: string
                  description: Required. The segment name. Maximum 128 characters.
                  default: YOUR_SEGMENT_NAME
                description:
                  type: string
                  description: >-
                    Optional human-readable description for the segment. Maximum
                    255 characters. Pass an empty string to clear; omit to leave
                    unchanged.
                  maxLength: 255
                  default: YOUR_SEGMENT_DESCRIPTION
                filters:
                  type: array
                  description: >-
                    Optional. When provided, replaces all existing filters.
                    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 [Create segment](/reference/create-segments)
                    for filter syntax.
                  items:
                    oneOf:
                      - title: Filter
                        description: Required. The filter 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:
        '200':
          description: '200'
          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 updated successfully, false
                      otherwise.
                    default: true
                  id:
                    type: string
                    description: The UUID of the updated segment.
        '400':
          description: '400'
          content:
            application/json:
              examples:
                Result:
                  value:
                    success: false
                    errors:
                      - Segment name is already taken.
              schema:
                $ref: '#/components/schemas/BasicErrorResponse'
        '403':
          description: '403'
          content:
            application/json:
              examples:
                Result:
                  value:
                    success: false
                    errors:
                      - This API is not available for applications on your plan.
              schema:
                $ref: '#/components/schemas/BasicErrorResponse'
        '404':
          description: '404'
          content:
            application/json:
              examples:
                Result:
                  value:
                    success: false
                    errors:
                      - segment not found
              schema:
                $ref: '#/components/schemas/BasicErrorResponse'
        '429':
          description: '429'
          content:
            application/json:
              examples:
                Result:
                  value:
                    errors:
                      - code: Rate Limit Exceeded
                        title: Example error title
                        meta: {}
              schema:
                $ref: '#/components/schemas/StructuredErrorResponse'
          headers:
            Retry-After:
              description: >-
                Number of seconds to wait before retrying the request. Always
                emitted on 429 responses.
              schema:
                type: integer
                minimum: 0
        '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 the request. This
                header is optional and may be absent when a proxy or load
                balancer generates the 503.
              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 = "YOUR_APP_ID";

            // string | The segment\'s unique identifier. Can be found using the
            View Segments API or in the URL of the segment when viewing it in
            the dashboard.

            const segmentId: string = "d6c5a3e1-9f17-44a1-9d10-7c0e4a2b1c8e";

            // UpdateSegmentRequest (optional)

            const updateSegmentRequest: Onesignal.UpdateSegmentRequest = {
                name: "name_example",
                description: "description_example",
                filters: [
                  {
                    field: "tag",
                    key: "level",
                    value: "10",
                    hours_ago: "24",
                    radius: 3.14,
                    lat: 3.14,
                    long: 3.14,
                    relation: ">",
                  },
                ],
              };

            try {
              const response = await apiInstance.updateSegment(appId, segmentId, updateSegmentRequest);
              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("updateSegment 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 = "YOUR_APP_ID" # The OneSignal App ID for your app.  Available in Keys & IDs. 
                segment_id = "d6c5a3e1-9f17-44a1-9d10-7c0e4a2b1c8e" # The segment's unique identifier. Can be found using the View Segments API or in the URL of the segment when viewing it in the dashboard. 
                update_segment_request = UpdateSegmentRequest(
                    name="name_example",
                    description="description_example",
                    filters=[
                        Filter(
                            field="tag",
                            key="level",
                            value="10",
                            hours_ago="24",
                            radius=3.14,
                            lat=3.14,
                            long=3.14,
                            relation=">",
                        ),
                    ],
                ) 

                try:
                    # Update Segment
                    api_response = api_instance.update_segment(app_id, segment_id, update_segment_request=update_segment_request)
                    pprint(api_response)
                except onesignal.ApiException as e:
                    print("Exception when calling DefaultApi->update_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 = 'YOUR_APP_ID'; // string | The OneSignal App ID for your
            app.  Available in Keys & IDs.

            $segment_id = 'd6c5a3e1-9f17-44a1-9d10-7c0e4a2b1c8e'; // string |
            The segment's unique identifier. Can be found using the View
            Segments API or in the URL of the segment when viewing it in the
            dashboard.

            $update_segment_request = new
            \onesignal\client\model\UpdateSegmentRequest(); //
            \onesignal\client\model\UpdateSegmentRequest


            try {
                $result = $apiInstance->updateSegment($app_id, $segment_id, $update_segment_request);
                print_r($result);
            } catch (\onesignal\client\ApiException $e) {
                echo 'Exception when calling DefaultApi->updateSegment: ', $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->updateSegment: ', $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 := "YOUR_APP_ID" // string | The OneSignal App ID for your app.  Available in Keys & IDs.
                segmentId := "d6c5a3e1-9f17-44a1-9d10-7c0e4a2b1c8e" // string | The segment's unique identifier. Can be found using the View Segments API or in the URL of the segment when viewing it in the dashboard.
                updateSegmentRequest := *onesignal.NewUpdateSegmentRequest("Name_example") // UpdateSegmentRequest |  (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.UpdateSegment(restAuth, appId, segmentId).UpdateSegmentRequest(updateSegmentRequest).Execute()

                if err != nil {
                    fmt.Fprintf(os.Stderr, "Error when calling `DefaultApi.UpdateSegment``: %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 `UpdateSegment`: UpdateSegmentSuccessResponse
                fmt.Fprintf(os.Stdout, "Response from `DefaultApi.UpdateSegment`: %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 = 'YOUR_APP_ID' # String | The OneSignal App ID for your
            app.  Available in Keys & IDs.

            segment_id = 'd6c5a3e1-9f17-44a1-9d10-7c0e4a2b1c8e' # String | The
            segment's unique identifier. Can be found using the View Segments
            API or in the URL of the segment when viewing it in the dashboard.

            opts = {
              update_segment_request: OneSignal::UpdateSegmentRequest.new({name: 'name_example'}) # UpdateSegmentRequest | 
            }


            begin
              # Update Segment
              result = api_instance.update_segment(app_id, segment_id, opts)
              p result
            rescue OneSignal::ApiError => e
              puts "Error when calling DefaultApi->update_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 = "YOUR_APP_ID"; // String | The OneSignal App ID for your app.  Available in Keys & IDs.
                String segmentId = "d6c5a3e1-9f17-44a1-9d10-7c0e4a2b1c8e"; // String | The segment's unique identifier. Can be found using the View Segments API or in the URL of the segment when viewing it in the dashboard.
                UpdateSegmentRequest updateSegmentRequest = new UpdateSegmentRequest(); // UpdateSegmentRequest | 
                try {
                  UpdateSegmentSuccessResponse result = apiInstance.updateSegment(appId, segmentId, updateSegmentRequest);
                  System.out.println(result);
                } catch (ApiException e) {
                  System.err.println("Exception when calling DefaultApi#updateSegment");
                  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 UpdateSegmentExample
                {
                    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 = "YOUR_APP_ID";  // string | The OneSignal App ID for your app.  Available in Keys & IDs.
                        var segmentId = "d6c5a3e1-9f17-44a1-9d10-7c0e4a2b1c8e";  // string | The segment's unique identifier. Can be found using the View Segments API or in the URL of the segment when viewing it in the dashboard.
                        var updateSegmentRequest = new UpdateSegmentRequest(); // UpdateSegmentRequest |  (optional) 

                        try
                        {
                            // Update Segment
                            UpdateSegmentSuccessResponse result = apiInstance.UpdateSegment(appId, segmentId, updateSegmentRequest);
                            Debug.WriteLine(result);
                        }
                        catch (ApiException  e)
                        {
                            Debug.Print("Exception when calling DefaultApi.UpdateSegment: " + 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 = "YOUR_APP_ID";
                let segment_id: &str = "d6c5a3e1-9f17-44a1-9d10-7c0e4a2b1c8e";
                let update_segment_request: Option<models::UpdateSegmentRequest> = None;

                match default_api::update_segment(&configuration, app_id, segment_id, update_segment_request).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!("update_segment failed: {:?}", e.error_messages());
                    }
                    Err(e) => eprintln!("update_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.
    StructuredErrorResponse:
      type: object
      properties:
        errors:
          type: array
          items:
            $ref: '#/components/schemas/StructuredErrorItem'
    StructuredErrorItem:
      type: object
      required:
        - code
        - title
      properties:
        code:
          type: string
          description: >-
            Stable error-code identifier. Use this for programmatic branching in
            your integration.
        title:
          type: string
          description: >-
            Human-readable error message intended for logs and operator-facing
            surfaces.
        meta:
          type: object
          additionalProperties: true
          description: >-
            Optional extra details for this error. Properties depend on `code`.
            For create-user `Conflict`, `meta.conflicting_aliases` maps each
            colliding alias label to the alias ID already bound to another user.

````