# Get Segment by ID

## 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/{segment_id}","method":"get","servers":[{"url":"https://api.sendgrid.com","description":"The Twilio SendGrid v3 API"}]}
```

**This endpoint allows you to retrieve a single segment by ID.**

## Operation details

### Authentication

API Key

### Headers

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

### Path parameters

```json
[{"name":"segment_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","minLength":36,"maxLength":36}}]
```

### Query string

```json
[{"name":"query_json","in":"query","description":"Defaults to `false`.  Set to `true` to return the parsed SQL AST as a JSON object in the field `query_json`","schema":{"type":"boolean"}}]
```

### Responses

```json
[{"responseCode":"200","schema":{"description":"","content":{"application/json":{"schema":{"title":"full_segment","example":{"id":"58567a46-305e-48d1-b4f8-a006c906920e","contacts_count":9266921,"created_at":"2085-08-08T21:07:05.692Z","sample_updated_at":"3407-09-25T04:25:02.140Z","updated_at":"4431-05-07T22:23:22.352Z","contacts_sample":[{"id":"c1183ada-b784-49ac-9b1f-50e73578a6dc","email":"ft88@d.izxx","external_id":"1234","alternate_emails":["yKDUP11FDch@QoU.vwy","ZNSN5@czAMqPi.at","7wr51kFVVKlcBSH@DWxOueOZepetzBrku.qosk","iib-ObtO7Fxz5@vLJPRIFKPOqJGCEqcIDab.ypn"],"first_name":"est","last_name":"eiusmod in laboris velit cupidatat","address_line_1":"sunt aliqua","address_line_2":"sit proident Lorem veniam labore","city":"ȎţȸÛ\tč\u000bCŁ","state_province_region":"ut proident","postal_code":30296612,"country":"do reprehenderit qui","custom_fields":{"custom_field_name2":"in consectetur ut aliqua sint","custom_field_name1":"esse"}}],"name":"culpa","query_dsl":"cillum eiusmod","parent_list_id":"2357714d-3d82-4c80-826c-b44a4147f81c","next_sample_update":""},"type":"object","required":["contacts_count","contacts_sample","created_at","id","name","query_dsl","sample_updated_at","updated_at"],"refName":"FullSegment","modelName":"FullSegment","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,"description":"Name of the segment."},"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."},"contacts_sample":{"type":"array","items":{"title":"contact_response","type":"object","required":["id","alternate_emails","first_name","last_name","address_line_1","address_line_2","city","state_province_region","postal_code","country","custom_fields"],"example":{"id":"47d23ab0-d895-4359-a0d1-ffc7a6fc7e70","email":"abcd@gmail.com","alternate_emails":["abcd@yahoo.com","abcd@hotmail.com"],"first_name":"Ab","last_name":"Cd","address_line_1":"street address / P.O. box / CompanyName / c/o","address_line_2":"apartment, suite, unit, building, floor etc","city":"Redwood City","state_province_region":"CA","postal_code":94063,"country":"USA","custom_fields":{"custom_field_name1":"custom_field_value1","custom_field_name2":"custom_field_value2"}},"refName":"ContactResponse","modelName":"ContactResponse","properties":{"id":{"type":"string","maxLength":36,"pattern":"[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}","format":"uuid","description":"ID assigned to a contact when added to the system."},"email":{"type":"string","minLength":3,"maxLength":254,"format":"email","description":"Email of the contact. This is a reserved field."},"phone_number_id":{"type":"string","description":"The contact's Phone Number ID. This must be a valid phone number."},"external_id":{"type":"string","description":"The contact's External ID.","maxLength":254},"anonymous_id":{"type":"string","description":"The contact's Anonymous ID.","maxLength":254},"alternate_emails":{"type":"array","uniqueItems":true,"minItems":0,"description":"Alternate emails of the contact. This is a reserved field.","items":{"type":"string","minLength":3,"maxLength":254,"format":"email"}},"first_name":{"type":"string","minLength":1,"description":"First name of the contact. This is a reserved field."},"last_name":{"type":"string","minLength":1,"description":"Last name of the contact. This is a reserved field."},"address_line_1":{"type":"string","minLength":0,"description":"First line of address of the contact. This is a reserved field."},"address_line_2":{"type":"string","minLength":0,"description":"Second line of address of the contact. This is a reserved field."},"city":{"type":"string","minLength":0,"pattern":"^[a-zA-Z\\u0080-\\u024F\\s\\/\\-\\)\\(\\`\\.\\\"\\']+$","description":"City associated with the contact. This is a reserved field."},"state_province_region":{"type":"string","minLength":0,"description":"State associated with the contact. This is a reserved field."},"postal_code":{"type":"integer","description":"Zipcode associated with the address of the contact. This is a reserved field."},"country":{"type":"string","minLength":0,"description":"Country associated with the address of the contact. This is a reserved field."},"list_ids":{"type":"array","uniqueItems":true,"description":"IDs of all lists the contact is part of","items":{"type":"string","format":"uuid"}},"custom_fields":{"type":"object","minProperties":0,"description":"The user may choose to create up to 120 custom fields or none at all. This is not a reserved field.","properties":{"custom_field_name1":{"type":"string","minLength":0},"custom_field_name2":{"type":"string","minLength":0}}},"segment_ids":{"type":"array","uniqueItems":true,"description":"IDs of all segments the contact is part of","items":{"type":"string","format":"uuid"}}}}},"query_json":{"type":"object","description":"AST representation of the query DSL"},"parent_list_ids":{"type":"array","description":"The array of list ids to filter contacts on when building this segment. It allows only one such list id for now. We will support more in future","uniqueItems":true,"items":{"type":"string"}},"query_dsl":{"type":"string","description":"SQL query which will filter contacts based on the conditions provided"}}},"examples":{"response":{"value":{"id":"3b049926-0a54-4a91-83f0-086ace63c530","contacts_count":-83213117,"created_at":"2921-01-27T19:33:36.479Z","sample_updated_at":"3407-09-25T04:25:02.140Z","updated_at":"4389-06-21T16:59:51.403Z","contacts_sample":[{"id":"e70eac25-1431-4231-bccd-1cfab432301e","email":"KLTF@SurgGzlAxCPOqhOUHYNBLsfpfE.trh","alternate_emails":["dTeJZgU5uN9UYSo@nfIB.ijxg"],"first_name":"ullamco esse culpa do","last_name":"officia laboris veniam consequat","address_line_1":"in occaecat labore est tempor","address_line_2":"magna adipisicing","city":"ƞó","state_province_region":"culpa ut","postal_code":-75218567,"country":"voluptate in in reprehenderit aliquip","custom_fields":{"custom_field_name1":"amet deserunt mollit","custom_field_name2":"minim consequat id"}},{"id":"db637d33-bce1-462c-ae9c-91ec4f761de6","email":"t7N5TjDmKhC0@gfdifW.ua","alternate_emails":["gQol@Xcfilli.hc","n4K7OdaVQh@YfsnF.ie","TdnvS3nMStREn@miFjGzNDCPZWhiswJNxrFnOYdUAZEpesQ.yxpu","xRzGDTTzzbYK@eJ.wpgb","iI1rOpx2ct@aZhuYGZBxJLZ.phr"],"first_name":"ea et eu","last_name":"velit Ut laborum ipsu","address_line_1":"labore","address_line_2":"non","city":"ĔȸąÂ¸ȠɏbɄ","state_province_region":"deserunt dolore","postal_code":-95171713,"country":"do","list_ids":["c712288b-2300-4069-bef4-2e05b5948ec3","9003ef29-5eb7-4951-898b-1b102e490d6e"],"custom_fields":{"custom_field_name1":"amet deserunt mollit","custom_field_name2":"minim consequat id"}}],"name":"enim et anim","query_dsl":"nostrud"}}}}}}},{"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","required":["errors"],"properties":{"errors":{"type":"array","items":{"type":"object","required":["message","field"],"properties":{"message":{"type":"string"},"field":{"type":"string"}}}}}}}}}},{"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 Segment by ID

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

const segment_id = "f15982c1-a82c-4e87-a6b2-a4a63b4b7644";

const request = {
  url: `/v3/marketing/segments/${segment_id}`,
  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"))

segment_id = "f15982c1-a82c-4e87-a6b2-a4a63b4b7644"

response = sg.client.marketing.segments._(segment_id).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 segmentId = "f15982c1-a82c-4e87-a6b2-a4a63b4b7644";

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

        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/f15982c1-a82c-4e87-a6b2-a4a63b4b7644");
            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/f15982c1-a82c-4e87-a6b2-a4a63b4b7644", 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);
$segment_id = "f15982c1-a82c-4e87-a6b2-a4a63b4b7644";

try {
    $response = $sg->client
        ->marketing()
        ->segments()
        ->_($segment_id)
        ->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'])
segment_id = "f15982c1-a82c-4e87-a6b2-a4a63b4b7644"

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

```bash
curl -X GET "https://api.sendgrid.com/v3/marketing/segments/f15982c1-a82c-4e87-a6b2-a4a63b4b7644" \
--header "Authorization: Bearer $SENDGRID_API_KEY"
```
