# List segments

GET https://app.launchdarkly.com/api/v2/segments/{projectKey}/{environmentKey}

Get a list of all segments in the given project.

Segments can be rule-based, list-based, or synced. Big segments include larger list-based segments and synced segments. Some fields in the response only apply to big segments.

### Filtering segments

The `filter` parameter supports the following operators: `equals`, `anyOf`, and `exists`.

You can also combine filters in the following ways:

- Use a comma (`,`) as an AND operator
- Use a vertical bar (`|`) as an OR operator
- Use parentheses (`()`) to group filters

#### Supported fields and operators

You can only filter certain fields in segments when using the `filter` parameter. Additionally, you can only filter some fields with certain operators.

When you search for segments, the `filter` parameter supports the following fields and operators:

|<div style="width:120px">Field</div> |Description |Supported operators |
|---|---|---|
| `excludedKeys` | The segment keys of segments to exclude from the results. | `anyOf` |
| `external` | Whether the segment is a synced segment. | `exists` |
| `includedKeys` | The segment keys of segments to include in the results. | `anyOf` |
| `query` | A "fuzzy" search across segment key, name, and description. Supply a string or list of strings to the operator. | `equals` |
| `tags` | The segment tags. | `anyOf` |
| `unbounded` | Whether the segment is a standard segment (`false`) or a big segment (`true`). Standard segments include rule-based segments and smaller list-based segments. Big segments include larger list-based segments and synced segments. | `equals` |

Here are a few examples:

* The filter `?filter=tags anyOf ["enterprise", "beta"],query equals "toggle"` matches segments with "toggle" in their key, name, or description that also have "enterprise" or "beta" as a tag.
* The filter `?filter=excludedKeys anyOf ["segmentKey1", "segmentKey2"]` excludes the segments with those keys from the results.
* The filter `?filter=unbounded equals true` matches larger list-based segments and synced segments.

The documented values for `filter` query parameters are prior to URL encoding. For example, the `[` in `?filter=tags anyOf ["enterprise", "beta"]` must be encoded to `%5B`.


Reference: https://launchdarkly.com/docs/api/segments/get-segments

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: LaunchDarkly REST API
  version: 1.0.0
paths:
  /api/v2/segments/{projectKey}/{environmentKey}:
    get:
      operationId: get-segments
      summary: List segments
      description: >
        Get a list of all segments in the given project.


        Segments can be rule-based, list-based, or synced. Big segments include
        larger list-based segments and synced segments. Some fields in the
        response only apply to big segments.


        ### Filtering segments


        The `filter` parameter supports the following operators: `equals`,
        `anyOf`, and `exists`.


        You can also combine filters in the following ways:


        - Use a comma (`,`) as an AND operator

        - Use a vertical bar (`|`) as an OR operator

        - Use parentheses (`()`) to group filters


        #### Supported fields and operators


        You can only filter certain fields in segments when using the `filter`
        parameter. Additionally, you can only filter some fields with certain
        operators.


        When you search for segments, the `filter` parameter supports the
        following fields and operators:


        |<div style="width:120px">Field</div> |Description |Supported operators
        |

        |---|---|---|

        | `excludedKeys` | The segment keys of segments to exclude from the
        results. | `anyOf` |

        | `external` | Whether the segment is a synced segment. | `exists` |

        | `includedKeys` | The segment keys of segments to include in the
        results. | `anyOf` |

        | `query` | A "fuzzy" search across segment key, name, and description.
        Supply a string or list of strings to the operator. | `equals` |

        | `tags` | The segment tags. | `anyOf` |

        | `unbounded` | Whether the segment is a standard segment (`false`) or a
        big segment (`true`). Standard segments include rule-based segments and
        smaller list-based segments. Big segments include larger list-based
        segments and synced segments. | `equals` |


        Here are a few examples:


        * The filter `?filter=tags anyOf ["enterprise", "beta"],query equals
        "toggle"` matches segments with "toggle" in their key, name, or
        description that also have "enterprise" or "beta" as a tag.

        * The filter `?filter=excludedKeys anyOf ["segmentKey1", "segmentKey2"]`
        excludes the segments with those keys from the results.

        * The filter `?filter=unbounded equals true` matches larger list-based
        segments and synced segments.


        The documented values for `filter` query parameters are prior to URL
        encoding. For example, the `[` in `?filter=tags anyOf ["enterprise",
        "beta"]` must be encoded to `%5B`.
      tags:
        - subpackage_segments
      parameters:
        - name: projectKey
          in: path
          description: The project key
          required: true
          schema:
            type: string
            format: string
        - name: environmentKey
          in: path
          description: The environment key
          required: true
          schema:
            type: string
            format: string
        - name: limit
          in: query
          description: The number of segments to return. Defaults to 20.
          required: false
          schema:
            type: integer
            format: int64
        - name: offset
          in: query
          description: >-
            Where to start in the list. Use this with pagination. For example,
            an offset of 10 skips the first ten items and then returns the next
            items in the list, up to the query `limit`.
          required: false
          schema:
            type: integer
            format: int64
        - name: sort
          in: query
          description: >-
            Accepts sorting order and fields. Fields can be comma separated.
            Possible fields are 'creationDate', 'name', 'lastModified'. Example:
            `sort=name` sort by names ascending or `sort=-name,creationDate`
            sort by names descending and creationDate ascending.
          required: false
          schema:
            type: string
            format: string
        - name: filter
          in: query
          description: >-
            Accepts filter by `excludedKeys`, `external`, `includedKeys`,
            `query`, `tags`, `unbounded`, `view`. To learn more about the filter
            syntax, read the  'Filtering segments' section above.
          required: false
          schema:
            type: string
            format: string
        - name: Authorization
          in: header
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Segment collection response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserSegments'
        '401':
          description: Invalid access token
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UnauthorizedErrorRep'
        '404':
          description: Invalid resource identifier
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NotFoundErrorRep'
servers:
  - url: https://app.launchdarkly.com
  - url: https://app.launchdarkly.us
components:
  schemas:
    UnixMillis:
      type: integer
      format: int64
      title: UnixMillis
    SegmentTarget:
      type: object
      properties:
        values:
          type: array
          items:
            type: string
        contextKind:
          type: string
      title: SegmentTarget
    Link:
      type: object
      properties:
        href:
          type: string
          description: The URL of the link
        type:
          type: string
          description: The type of the link
      title: Link
    Operator:
      type: string
      title: Operator
    Clause:
      type: object
      properties:
        _id:
          type: string
        attribute:
          type: string
        op:
          $ref: '#/components/schemas/Operator'
        values:
          type: array
          items:
            description: Any type
        contextKind:
          type: string
        negate:
          type: boolean
      required:
        - attribute
        - op
        - values
        - negate
      title: Clause
    UserSegmentRule:
      type: object
      properties:
        _id:
          type: string
        clauses:
          type: array
          items:
            $ref: '#/components/schemas/Clause'
        weight:
          type: integer
        rolloutContextKind:
          type: string
        bucketBy:
          type: string
        description:
          type: string
      required:
        - clauses
      title: UserSegmentRule
    ActionIdentifier:
      type: string
      title: ActionIdentifier
    ActionSpecifier:
      type: string
      title: ActionSpecifier
    AccessDeniedReasonEffect:
      type: string
      enum:
        - allow
        - deny
      description: Whether this statement should allow or deny actions on the resources.
      title: AccessDeniedReasonEffect
    AccessDeniedReason:
      type: object
      properties:
        resources:
          type: array
          items:
            type: string
          description: Resource specifier strings
        notResources:
          type: array
          items:
            type: string
          description: >-
            Targeted resources are the resources NOT in this list. The
            <code>resources</code> and <code>notActions</code> fields must be
            empty to use this field.
        actions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: Actions to perform on a resource
        notActions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: >-
            Targeted actions are the actions NOT in this list. The
            <code>actions</code> and <code>notResources</code> fields must be
            empty to use this field.
        effect:
          $ref: '#/components/schemas/AccessDeniedReasonEffect'
          description: >-
            Whether this statement should allow or deny actions on the
            resources.
        role_name:
          type: string
      required:
        - effect
      title: AccessDeniedReason
    AccessDenied:
      type: object
      properties:
        action:
          $ref: '#/components/schemas/ActionIdentifier'
        reason:
          $ref: '#/components/schemas/AccessDeniedReason'
      required:
        - action
        - reason
      title: AccessDenied
    AccessAllowedReasonEffect:
      type: string
      enum:
        - allow
        - deny
      description: Whether this statement should allow or deny actions on the resources.
      title: AccessAllowedReasonEffect
    AccessAllowedReason:
      type: object
      properties:
        resources:
          type: array
          items:
            type: string
          description: Resource specifier strings
        notResources:
          type: array
          items:
            type: string
          description: >-
            Targeted resources are the resources NOT in this list. The
            <code>resources</code> and <code>notActions</code> fields must be
            empty to use this field.
        actions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: Actions to perform on a resource
        notActions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: >-
            Targeted actions are the actions NOT in this list. The
            <code>actions</code> and <code>notResources</code> fields must be
            empty to use this field.
        effect:
          $ref: '#/components/schemas/AccessAllowedReasonEffect'
          description: >-
            Whether this statement should allow or deny actions on the
            resources.
        role_name:
          type: string
      required:
        - effect
      title: AccessAllowedReason
    AccessAllowedRep:
      type: object
      properties:
        action:
          $ref: '#/components/schemas/ActionIdentifier'
        reason:
          $ref: '#/components/schemas/AccessAllowedReason'
      required:
        - action
        - reason
      title: AccessAllowedRep
    Access:
      type: object
      properties:
        denied:
          type: array
          items:
            $ref: '#/components/schemas/AccessDenied'
        allowed:
          type: array
          items:
            $ref: '#/components/schemas/AccessAllowedRep'
      required:
        - denied
        - allowed
      title: Access
    FlagListingRep:
      type: object
      properties:
        name:
          type: string
          description: The flag name
        key:
          type: string
          description: The flag key
        _links:
          type: object
          additionalProperties:
            $ref: '#/components/schemas/Link'
        _site:
          $ref: '#/components/schemas/Link'
      required:
        - name
        - key
      title: FlagListingRep
    SegmentId:
      type: string
      title: SegmentId
    SegmentMetadata:
      type: object
      properties:
        envId:
          type: string
        segmentId:
          $ref: '#/components/schemas/SegmentId'
        version:
          type: integer
        includedCount:
          type: integer
        excludedCount:
          type: integer
        lastModified:
          $ref: '#/components/schemas/UnixMillis'
        deleted:
          type: boolean
      title: SegmentMetadata
    UserSegment:
      type: object
      properties:
        name:
          type: string
          description: A human-friendly name for the segment.
        description:
          type: string
          description: >-
            A description of the segment's purpose. Defaults to
            <code>null</code> and is omitted in the response if not provided.
        tags:
          type: array
          items:
            type: string
          description: Tags for the segment. Defaults to an empty array.
        creationDate:
          $ref: '#/components/schemas/UnixMillis'
          description: Timestamp of when the segment was created
        lastModifiedDate:
          $ref: '#/components/schemas/UnixMillis'
          description: Timestamp of when the segment was last modified
        key:
          type: string
          description: A unique key used to reference the segment
        included:
          type: array
          items:
            type: string
          description: >-
            An array of keys for included targets. Included individual targets
            are always segment members, regardless of segment rules. For
            list-based segments over 15,000 entries, also called big segments,
            this array is either empty or omitted.
        excluded:
          type: array
          items:
            type: string
          description: >-
            An array of keys for excluded targets. Segment rules bypass
            individual excluded targets, so they will never be included based on
            rules. Excluded targets may still be included explicitly. This value
            is omitted for list-based segments over 15,000 entries, also called
            big segments.
        includedContexts:
          type: array
          items:
            $ref: '#/components/schemas/SegmentTarget'
        excludedContexts:
          type: array
          items:
            $ref: '#/components/schemas/SegmentTarget'
        _links:
          type: object
          additionalProperties:
            $ref: '#/components/schemas/Link'
          description: The location and content type of related resources
        rules:
          type: array
          items:
            $ref: '#/components/schemas/UserSegmentRule'
          description: An array of the targeting rules for this segment.
        version:
          type: integer
          description: Version of the segment
        deleted:
          type: boolean
          description: Whether the segment has been deleted
        _access:
          $ref: '#/components/schemas/Access'
        _flags:
          type: array
          items:
            $ref: '#/components/schemas/FlagListingRep'
          description: >-
            A list of flags targeting this segment. Only included when getting a
            single segment, using the <code>getSegment</code> endpoint.
        unbounded:
          type: boolean
          description: >-
            Whether this is a standard segment (<code>false</code>) or a big
            segment (<code>true</code>). Standard segments include rule-based
            segments and smaller list-based segments. Big segments include
            larger list-based segments and synced segments. If omitted, the
            segment is a standard segment.
        unboundedContextKind:
          type: string
          description: For big segments, the targeted context kind.
        generation:
          type: integer
          description: For big segments, how many times this segment has been created.
        _unboundedMetadata:
          $ref: '#/components/schemas/SegmentMetadata'
          description: >-
            Details on the external data store backing this segment. Only
            applies to big segments.
        _external:
          type: string
          description: >-
            The external data store backing this segment. Only applies to synced
            segments.
        _externalLink:
          type: string
          description: >-
            The URL for the external data store backing this segment. Only
            applies to synced segments.
        _importInProgress:
          type: boolean
          description: >-
            Whether an import is currently in progress for the specified
            segment. Only applies to big segments.
      required:
        - name
        - tags
        - creationDate
        - lastModifiedDate
        - key
        - _links
        - rules
        - version
        - deleted
        - generation
      title: UserSegment
    UserSegments:
      type: object
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/UserSegment'
          description: An array of segments
        _links:
          type: object
          additionalProperties:
            $ref: '#/components/schemas/Link'
          description: The location and content type of related resources
        totalCount:
          type: integer
          description: The total number of segments
      required:
        - items
        - _links
      title: UserSegments
    UnauthorizedErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: UnauthorizedErrorRep
    NotFoundErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: NotFoundErrorRep
  securitySchemes:
    ApiKey:
      type: apiKey
      in: header
      name: Authorization

```

## SDK Code Examples

```python
import requests

url = "https://app.launchdarkly.com/api/v2/segments/projectKey/environmentKey"

headers = {"Authorization": "<apiKey>"}

response = requests.get(url, headers=headers)

print(response.json())
```

```javascript
const url = 'https://app.launchdarkly.com/api/v2/segments/projectKey/environmentKey';
const options = {method: 'GET', headers: {Authorization: '<apiKey>'}};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"net/http"
	"io"
)

func main() {

	url := "https://app.launchdarkly.com/api/v2/segments/projectKey/environmentKey"

	req, _ := http.NewRequest("GET", url, nil)

	req.Header.Add("Authorization", "<apiKey>")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://app.launchdarkly.com/api/v2/segments/projectKey/environmentKey")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Get.new(url)
request["Authorization"] = '<apiKey>'

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.get("https://app.launchdarkly.com/api/v2/segments/projectKey/environmentKey")
  .header("Authorization", "<apiKey>")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('GET', 'https://app.launchdarkly.com/api/v2/segments/projectKey/environmentKey', [
  'headers' => [
    'Authorization' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://app.launchdarkly.com/api/v2/segments/projectKey/environmentKey");
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "<apiKey>");
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = ["Authorization": "<apiKey>"]

let request = NSMutableURLRequest(url: NSURL(string: "https://app.launchdarkly.com/api/v2/segments/projectKey/environmentKey")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```