# Update Segment

## API Overview

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 V2 API allows you to create, edit, and delete segments as well as retrieve a list of segments or an individual segment by ID.

Segments built using engagement data such as "was sent" or "clicked" will take approximately 30 minutes to begin populating.

Segment samples and counts refresh on a schedule that ranges from 1 to 24 hours. Segments with active automations or that are used as exclusion lists for scheduled Single Sends refresh every hour. Segments that aren't actively used refresh less frequently, up to every 24 hours, to optimize processing resources. Samples and counts displayed in the UI don't update immediately when segment criteria are modified or when contacts are added or updated. Instead, they update according to the segment's refresh schedule.

## Operation overview

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

Segment `name` has to be unique. A user can not create a new segment with an existing segment name.

## 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"}}]
```

### Request body

```json
{"schema":{"title":"segment_update","type":"object","refName":"SegmentUpdate","modelName":"SegmentUpdate","properties":{"name":{"type":"string","minLength":1,"maxLength":100,"description":"Name of the segment."},"query_dsl":{"type":"string","description":"SQL query which will filter contacts based on the conditions provided"}}},"encodingType":"application/json"}
```

### Responses

```json
[{"responseCode":"200","schema":{"description":"","content":{"application/json":{"schema":{"title":"segment_response","type":"object","required":["id","name","query_dsl","contacts_count","contacts_sample","created_at","updated_at","sample_updated_at","next_sample_update","parent_list_ids","query_version","status"],"refName":"Segment2xx","modelName":"Segment2xx","properties":{"id":{"type":"string","minLength":36,"maxLength":36,"format":"uuid","description":"ID assigned to the segment when created."},"name":{"type":"string","minLength":1,"maxLength":100,"description":"Name of the segment."},"query_dsl":{"type":"string","description":"SQL query which will filter contacts based on the conditions provided"},"contacts_count":{"type":"integer","description":"Total number of contacts present in the segment"},"contacts_sample":{"type":"array","description":"A subset of all contacts that are in this segment","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"}}}}},"created_at":{"type":"string","description":"ISO8601 timestamp of when the object was created"},"updated_at":{"type":"string","description":"ISO8601 timestamp of when the object was last updated"},"sample_updated_at":{"type":"string","description":"ISO8601 timestamp of when the samples were last updated"},"next_sample_update":{"type":"string","description":"ISO8601 timestamp of when the samples will be next updated"},"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_version":{"type":"string","description":"If not set, segment contains a Query for use with Segment v1 APIs. If set to '2', segment contains a SQL query for use in v2."},"status":{"title":"segment_status_response","type":"object","description":"Segment status indicates whether the segment's contacts will be updated periodically","required":["query_validation"],"refName":"SegmentStatusResponse","modelName":"SegmentStatusResponse","properties":{"query_validation":{"type":"string","description":"Status of query validation. PENDING, VALID, or INVALID"},"error_message":{"type":"string","description":"Describes any errors that were encountered during query validation"}}},"refreshes_used":{"type":"integer","description":"The number of times a segment has been manually refreshed since start of today in the user's timezone."},"max_refreshes":{"type":"integer","description":"The maximum number of manual refreshes allowed per day for this segment. Currently, only 2 are allowed."},"last_refreshed_at":{"type":"string","description":"The ISO8601 timestamp when the segment was last refreshed in UTC time."}}}}}}},{"responseCode":"400","schema":{"description":"","content":{"application/json":{"schema":{"title":"errors-seg","type":"object","description":"If the request is incorrect, an array of errors will be returned.","required":["errors"],"refName":"ErrorsSegmentV2","modelName":"ErrorsSegmentV2","properties":{"errors":{"type":"array","items":{"type":"object","required":["field","message"],"properties":{"field":{"type":"string","description":"the field in the request body that is incorrect"},"message":{"type":"string","description":"a description of what is specifically wrong with the field passed in the request"}}}}}}}}}},{"responseCode":"429","schema":{"description":""}},{"responseCode":"500","schema":{"description":"","content":{"application/json":{"schema":{"title":"errors-seg","type":"object","description":"If the request is incorrect, an array of errors will be returned.","required":["errors"],"refName":"ErrorsSegmentV2","modelName":"ErrorsSegmentV2","properties":{"errors":{"type":"array","items":{"type":"object","required":["field","message"],"properties":{"field":{"type":"string","description":"the field in the request body that is incorrect"},"message":{"type":"string","description":"a description of what is specifically wrong with the field passed in the request"}}}}}}}}}}]
```

Update Segment

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

const segment_id = "segment_id";
const data = {
  name: "Miss Christine Morgan",
};

const request = {
  url: `/v3/marketing/segments/2.0/${segment_id}`,
  method: "PATCH",
  body: data,
};

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 = "segment_id"
data = {"name": "Miss Christine Morgan"}

response = sg.client._(f"marketing/segments/2.0/{segment_id}").patch(
    request_body=data
)

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 = "segment_id";
        var data =
            @"{
            ""name"": ""Miss Christine Morgan""
        }";

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

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

```java
import com.sendgrid.*;
import java.io.IOException;
import org.json.JSONObject;
import java.util.HashMap;

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.PATCH);
            request.setEndpoint("/marketing/segments/2.0/segment_id");
            request.setBody(new JSONObject(new HashMap<String, Object>() {
                {
                    put("name", "Miss Christine Morgan");
                }
            }).toString());
            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/2.0/segment_id", host)
	request.Method = "PATCH"
	request.Body = []byte(`{
  "name": "Miss Christine Morgan"
}`)
	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);
$request_body = json_decode('{
    "name": "Miss Christine Morgan"
}');
$segment_id = "segment_id";

try {
    $response = $sg->client
        ->_("marketing/segments/2.0/{$segment_id}")
        ->patch($request_body);
    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'])
data = JSON.parse('{
  "name": "Miss Christine Morgan"
}')
segment_id = "segment_id"

response = sg.client._("marketing/segments/2.0/#{segment_id}").patch(request_body: data)
puts response.status_code
puts response.headers
puts response.body
```

```bash
curl -X PATCH "https://api.sendgrid.com/v3/marketing/segments/2.0/segment_id" \
--header "Authorization: Bearer $SENDGRID_API_KEY" \
--header "Content-Type: application/json" \
--data '{"name": "Miss Christine Morgan"}'
```
