# Get List of Segments

## API Overview

> \[!NOTE]
>
> Segmentation V2 APIs are now available! See the [Getting Started](/docs/sendgrid/for-developers/sending-email/getting-started-the-marketing-campaigns-v2-segmentation-api) guide to find out what new features are available.

Segments are similar to contact lists, except they update dynamically over time as information stored about your contacts or the criteria used to define your segments changes. When you segment your audience, you are able to create personalized Automation emails and Single Sends that directly address the wants and needs of your particular audience.

The Marketing Campaigns Segments API allows you to create, edit, and delete segments as well as retrieve a list of segments or an individual segment by ID.

> \[!NOTE]
>
> Note that Twilio SendGrid checks for newly added or modified contacts who meet a segment's criteria on an hourly schedule. Only existing contacts who meet a segment's criteria will be included in the segment searches within 15 minutes.\
> Segments built using engagement data such as "was sent" or "clicked" will take approximately 30 minutes to begin populating.\
> Segment samples and counts are refreshed approximately once per hour; they do not update immediately. If no contacts are added to or removed from a segment since the last refresh, the sample and UI count displayed will be refreshed at increasing time intervals with a maximum sample and count refresh delay of 24 hours.

For more information on creating segments with the Twilio SendGrid Marketing Campaigns UI see ["Segmenting your Contacts."](/docs/sendgrid/ui/managing-contacts/segmenting-your-contacts/)

For help with Segmentation Query Language, see our [Segmentation Query Language reference](/docs/sendgrid/for-developers/sending-email/segmentation-query-language/)

> \[!WARNING]
>
> The [Segmentation v1 API](/docs/sendgrid/api-reference/segmenting-contacts/get-segment-by-id) was deprecated on December 31, 2022. Following deprecation, all segments created in the Marketing Campaigns user interface began using the [Segmentation v2 API](/docs/sendgrid/api-reference/segmenting-contacts-v2).
>
> To enable manual migration and data retrieval, the `GET` and `DELETE` v1 API endpoints will remain available. The `POST` (create) and `PATCH` (update) v1 endpoints were removed on January 31, 2023 because it is no longer possible to create new v1 segments or modify existing ones. See our [Segmentation v1 to v2 upgrade instructions](/docs/sendgrid/for-developers/sending-email/getting-started-the-marketing-campaigns-v2-segmentation-api#upgrade-a-v1-segment-to-v2) to manually migrate your segments to the v2 API.

## Operation overview

```json
{"path":"https://api.sendgrid.com/v3/marketing/segments","method":"get","servers":[{"url":"https://api.sendgrid.com","description":"The Twilio SendGrid v3 API"}]}
```

**This endpoint allows you to retrieve a list of segments.**

The query param `parent_list_ids` is treated as a filter.  Any match will be returned.  Zero matches will return a response code of 200 with an empty `results` array.

| `parent_list_ids` | `no_parent_list_id` | `ids` |                                  `result`                                  |
| ----------------: | :-----------------: | :---: | :------------------------------------------------------------------------: |
|             empty |        false        | empty |                             all segments values                            |
|         list\_ids |        false        | empty |                    segments filtered by list\_ids values                   |
|         list\_ids |         true        | empty | segments filtered by list\_ids and segments with no parent list\_ids empty |
|             empty |         true        | empty |                      segments with no parent list\_ids                     |
|          anything |       anything      |  ids  |                     segments with matching segment ids                     |

## Operation details

### Authentication

API Key

### Headers

```json
[{"in":"header","name":"Authorization","required":true,"default":"Bearer <<YOUR_API_KEY_HERE>>","schema":{"type":"string"}}]
```

### Query string

```json
[{"name":"ids","in":"query","description":"A list of segment IDs to retrieve. When this parameter is included, the `no_parent_list_ids` and `parent_list_ids` parameters are ignored and only segments with given IDs are returned.","required":false,"schema":{"type":"array","items":{"type":"string"}}},{"name":"parent_list_ids","in":"query","description":"A comma separated list of list ids to be used when searching for segments with the specified parent_list_id, no more than 50 is allowed","schema":{"type":"string"}},{"name":"no_parent_list_id","in":"query","description":"If set to `true` segments with an empty value of `parent_list_id` will be returned in the filter.  If the value is not present it defaults to 'false'.","schema":{"type":"boolean","default":false}}]
```

### Responses

```json
[{"responseCode":"200","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","required":["results"],"properties":{"results":{"type":"array","uniqueItems":true,"minItems":0,"items":{"title":"segment_summary","type":"object","required":["id","contacts_count","created_at","sample_updated_at","updated_at"],"refName":"SegmentSummary","modelName":"SegmentSummary","properties":{"id":{"type":"string","minLength":36,"maxLength":36,"format":"uuid"},"contacts_count":{"type":"integer"},"created_at":{"type":"string","description":"ISO8601 of created timestamp\n","format":"date-time"},"name":{"type":"string","minLength":1,"maxLength":100},"parent_list_id":{"type":"string","minLength":36,"maxLength":36,"format":"uuid","description":"The id of the list if this segment is a child of a list.  This implies the query `AND CONTAINS(list_ids, ${parent_list_id})`"},"sample_updated_at":{"type":"string","description":"ISO8601 timestamp the sample was last updated","format":"date-time"},"updated_at":{"type":"string","description":"ISO8601 timestamp the object was last updated","format":"date-time"},"next_sample_update":{"type":"string","description":"ISO8601 string that is equal to `sample_updated_at` plus an internally calculated offset that depends on how often contacts enter or exit segments as the scheduled pipeline updates the samples."}}}}}},"examples":{"response":{"value":{"results":[{"id":"12099613-91e5-4d09-a900-df7626325288","contacts_count":78434802,"created_at":"2921-01-27T19:33:36.479Z","sample_updated_at":"4685-11-26T07:05:04.660Z","updated_at":"2883-07-10T13:13:37.697Z"},{"id":"60c37015-3734-4c8e-b293-68cfa2ae4fa5","contacts_count":34177253,"created_at":"2575-07-26T23:17:20.984Z","sample_updated_at":"3074-09-04T09:49:58.127Z","updated_at":"5116-10-15T07:37:40.838Z","parent_list_id":"fd38af3d-3f69-4947-8dca-5fa967e7be82","name":"amet"}]}}}}}}},{"responseCode":"401","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}}}},"refName":"#/components/responses/Segments401","modelName":"__components_responses_Segments401"}},{"responseCode":"403","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}}}},"refName":"#/components/responses/Segments403","modelName":"__components_responses_Segments403"}},{"responseCode":"404","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}}}},"refName":"#/components/responses/Segments404","modelName":"__components_responses_Segments404"}},{"responseCode":"500","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","required":["errors"],"properties":{"errors":{"type":"array","items":{"type":"object","required":["message"],"properties":{"message":{"type":"string"}}}}}}}}}}]
```

Get List of Segments

```js
const client = require("@sendgrid/client");
client.setApiKey(process.env.SENDGRID_API_KEY);

const request = {
  url: `/v3/marketing/segments`,
  method: "GET",
};

client
  .request(request)
  .then(([response, body]) => {
    console.log(response.statusCode);
    console.log(response.body);
  })
  .catch((error) => {
    console.error(error);
  });
```

```python
import os
from sendgrid import SendGridAPIClient


sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY"))


response = sg.client.marketing.segments.get()

print(response.status_code)
print(response.body)
print(response.headers)
```

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SendGrid;

public class Program {
    public static async Task Main() {
        string apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
        var client = new SendGridClient(apiKey);

        var response = await client.RequestAsync(
            method: SendGridClient.Method.GET, urlPath: "marketing/segments");

        Console.WriteLine(response.StatusCode);
        Console.WriteLine(response.Body.ReadAsStringAsync().Result);
        Console.WriteLine(response.Headers.ToString());
    }
}
```

```java
import com.sendgrid.*;
import java.io.IOException;

public class Example {
    public static void main(String[] args) throws IOException {
        try {
            SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
            Request request = new Request();
            request.setMethod(Method.GET);
            request.setEndpoint("/marketing/segments");
            Response response = sg.api(request);
            System.out.println(response.getStatusCode());
            System.out.println(response.getBody());
            System.out.println(response.getHeaders());
        } catch (IOException ex) {
            throw ex;
        }
    }
}
```

```go
package main

import (
	"fmt"
	"github.com/sendgrid/sendgrid-go"
	"os"
)

func main() {
	apiKey := os.Getenv("SENDGRID_API_KEY")
	host := "https://api.sendgrid.com"
	request := sendgrid.GetRequest(apiKey, "/v3/marketing/segments", host)
	request.Method = "GET"
	response, err := sendgrid.API(request)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		fmt.Println(response.StatusCode)
		fmt.Println(response.Body)
		fmt.Println(response.Headers)
	}
}
```

```php
<?php
// Uncomment the next line if you're using a dependency loader (such as Composer) (recommended)
// require 'vendor/autoload.php';

// Uncomment next line if you're not using a dependency loader (such as Composer)
// require_once '<PATH TO>/sendgrid-php.php';

$apiKey = getenv("SENDGRID_API_KEY");
$sg = new \SendGrid($apiKey);

try {
    $response = $sg->client
        ->marketing()
        ->segments()
        ->get();
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $ex) {
    echo "Caught exception: " . $ex->getMessage();
}
```

```ruby
require 'sendgrid-ruby'
include SendGrid

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])

response = sg.client.marketing.segments.get()
puts response.status_code
puts response.headers
puts response.body
```

```bash
curl -X GET "https://api.sendgrid.com/v3/marketing/segments" \
--header "Authorization: Bearer $SENDGRID_API_KEY"
```
