# Create a Segment

## API Overview

> \[!WARNING]
>
> This covers the obsolete Legacy Marketing Campaigns API.

> \[!NOTE]
>
> For the most up-to-date information on the Segments API, please visit the [new Marketing Campaigns Segments v2 API](/docs/sendgrid/api-reference/segmenting-contacts-v2).

The Segments API allows you to create and manage segments for your contacts. Segments are used to group contacts based on conditions you set. For example, you might create a segment for contacts who have opened a certain number of your emails, or for contacts who have not opened any of your emails in the last 30 days.

## Operation overview

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

**This endpoint allows you to create a new segment.**

Valid operators for create and update depend on the type of the field for which you are searching.

**Dates**

* "eq", "ne", "lt" (before), "gt" (after)
  * You may use MM/DD/YYYY for day granularity or an epoch for second granularity.
* "empty", "not\_empty"
* "is within"
  * You may use an [ISO 8601 date format](https://en.wikipedia.org/wiki/ISO_8601) or the # of days.

**Text**

* "contains"
* "eq" (is/equals - matches the full field)
* "ne" (is not/not equals - matches any field where the entire field is not the condition value)
* "empty"
* "not\_empty"

**Numbers**

* "eq" (is/equals)
* "lt" (is less than)
* "gt" (is greater than)
* "empty"
* "not\_empty"

**Email Clicks and Opens**

* "eq" (opened)
* "ne" (not opened)

All field values must be a string.

Conditions using "eq" or "ne" for email clicks and opens should provide a "field" of either `clicks.campaign_identifier` or `opens.campaign_identifier`.
The condition value should be a string containing the id of a completed campaign.

The conditions list may contain multiple conditions, joined by an "and" or "or" in the "and\_or" field.

The first condition in the conditions list must have an empty "and\_or", and subsequent conditions must all specify an "and\_or".

## Operation details

### Authentication

API Key

### Headers

```json
[{"in":"header","name":"Authorization","required":true,"default":"Bearer <<YOUR_API_KEY_HERE>>","schema":{"type":"string"}},{"name":"on-behalf-of","in":"header","description":"The `on-behalf-of` header allows you to make API calls from a parent account on behalf of the parent's Subusers or customer accounts. You will use the parent account's API key when using this header. When making a call on behalf of a customer account, the property value should be \"account-id\" followed by the customer account's ID (e.g., `on-behalf-of: account-id <account-id>`). When making a call on behalf of a Subuser, the property value should be the Subuser's username (e.g., `on-behalf-of: <subuser-username>`). See [**On Behalf Of**](/docs/sendgrid/api-reference/how-to-use-the-sendgrid-v3-api/on-behalf-of) for more information.","required":false,"schema":{"type":"string"},"refName":"#/components/parameters/OnBehalfOf","modelName":"__components_parameters_OnBehalfOf"}]
```

### Request body

```json
{"schema":{"title":"Create a Segment request","type":"object","required":["name","conditions"],"example":{"name":"Last Name Miller","list_id":4,"conditions":[{"field":"last_name","value":"Miller","operator":"eq","and_or":""},{"field":"last_clicked","value":"01/02/2015","operator":"gt","and_or":"and"},{"field":"clicks.campaign_identifier","value":"513","operator":"eq","and_or":"or"}],"recipient_count":1234},"refName":"ContactdbSegments","modelName":"ContactdbSegments","properties":{"name":{"type":"string","description":"The name of this segment."},"list_id":{"type":"integer","description":"The list id from which to make this segment. Not including this ID will mean your segment is created from the main contactdb rather than a list."},"conditions":{"type":"array","description":"The conditions for a recipient to be included in this segment.","items":{"title":"ContactDB: Segments: Conditions","type":"object","required":["field","value","operator"],"refName":"ContactdbSegmentsConditions","modelName":"ContactdbSegmentsConditions","properties":{"field":{"type":"string"},"value":{"type":"string"},"operator":{"type":"string","enum":["eq","ne","lt","gt","contains"],"refName":"Operator","modelName":"Operator"},"and_or":{"type":"string","enum":["and","or",""],"refName":"AndOr","modelName":"AndOr"}}}},"recipient_count":{"type":"number","description":"The count of recipients in this list. This is not included on creation of segments."}}},"encodingType":"application/json"}
```

### Responses

```json
[{"responseCode":"200","schema":{"description":"","content":{"application/json":{"schema":{"title":"ContactDB:: Segments with ID","type":"object","required":["conditions","id","name"],"refName":"ContactdbSegmentsId200","modelName":"ContactdbSegmentsId200","properties":{"id":{"type":"number","description":"The ID of the segment."},"name":{"type":"string","description":"The name of this segment."},"list_id":{"type":"integer","description":"The list id from which to make this segment. Not including this ID will mean your segment is created from the main contactdb rather than a list."},"conditions":{"type":"array","description":"The conditions for a recipient to be included in this segment.","items":{"title":"ContactDB: Segments: Conditions","type":"object","required":["field","value","operator"],"refName":"ContactdbSegmentsConditions","modelName":"ContactdbSegmentsConditions","properties":{"field":{"type":"string"},"value":{"type":"string"},"operator":{"type":"string","enum":["eq","ne","lt","gt","contains"],"refName":"Operator","modelName":"Operator"},"and_or":{"type":"string","enum":["and","or",""],"refName":"AndOr","modelName":"AndOr"}}}},"recipient_count":{"type":"number","description":"The count of recipients in this list. This is not included on creation of segments."}}},"examples":{"response":{"value":{"id":1,"name":"Last Name Miller","list_id":4,"conditions":[{"field":"last_name","value":"Miller","operator":"eq","and_or":""},{"field":"last_clicked","value":"01/02/2015","operator":"gt","and_or":"and"},{"field":"clicks.campaign_identifier","value":"513","operator":"eq","and_or":"or"}],"recipient_count":0}}}}}}},{"responseCode":"400","schema":{"description":"The request was formatted incorrectly or missing required parameters.","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."}}},"examples":{"response":{"value":{"errors":[{"message":"request body is not valid json"},{"message":"invalid value is passed into one of the request body parameters"},{"field":"field","message":"field and set value is not passed into the request body"},{"field":"value","message":"value and set value is not passed into the request body"},{"field":"operator","message":"operator and set value is not passed into the request body"},{"field":"and_or","message":"and_or is not set on more than one condition and less than all conditions"},{"field":"and_or","message":"and_or is set on all conditions"},{"field":"and_or","message":"and_or is set on the only condition passed"},{"field":"and_or","message":"and_or and set value is not passed into the request body"},{"field":"list_id","message":"the list_id is not valid"},{"field":"name","message":"the name is not valid"}]}}}}}}},{"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."}}},"examples":{"response":{"value":{"errors":[{"field":null,"message":"authorization required"}]}}}}}}}]
```

Create a Segment

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

const data = {
  name: "Last Name Miller",
  list_id: 4,
  conditions: [
    {
      field: "last_name",
      value: "Miller",
      operator: "eq",
      and_or: "",
    },
    {
      field: "last_clicked",
      value: "01/02/2015",
      operator: "gt",
      and_or: "and",
    },
    {
      field: "clicks.campaign_identifier",
      value: "513",
      operator: "eq",
      and_or: "or",
    },
  ],
  recipient_count: 1234,
};

const request = {
  url: `/v3/contactdb/segments`,
  method: "POST",
  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"))

data = {
    "name": "Last Name Miller",
    "list_id": 4,
    "conditions": [
        {
            "field": "last_name",
            "value": "Miller",
            "operator": "eq",
            "and_or": "",
        },
        {
            "field": "last_clicked",
            "value": "01/02/2015",
            "operator": "gt",
            "and_or": "and",
        },
        {
            "field": "clicks.campaign_identifier",
            "value": "513",
            "operator": "eq",
            "and_or": "or",
        },
    ],
    "recipient_count": 1234,
}

response = sg.client.contactdb.segments.post(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 data =
            @"{
            ""name"": ""Last Name Miller"",
            ""list_id"": 4,
            ""conditions"": [
                {
                    ""field"": ""last_name"",
                    ""value"": ""Miller"",
                    ""operator"": ""eq"",
                    ""and_or"": """"
                },
                {
                    ""field"": ""last_clicked"",
                    ""value"": ""01/02/2015"",
                    ""operator"": ""gt"",
                    ""and_or"": ""and""
                },
                {
                    ""field"": ""clicks.campaign_identifier"",
                    ""value"": ""513"",
                    ""operator"": ""eq"",
                    ""and_or"": ""or""
                }
            ],
            ""recipient_count"": 1234
        }";

        var response = await client.RequestAsync(
            method: SendGridClient.Method.POST, urlPath: "contactdb/segments", 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;
import java.util.Arrays;

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.POST);
            request.setEndpoint("/contactdb/segments");
            request.setBody(new JSONObject(new HashMap<String, Object>() {
                {
                    put("name", "Last Name Miller");
                    put("list_id", 4);
                    put("conditions",
                        Arrays.asList(
                            new HashMap<String, Object>() {
                                {
                                    put("field", "last_name");
                                    put("value", "Miller");
                                    put("operator", "eq");
                                    put("and_or", "");
                                }
                            },
                            new HashMap<String, Object>() {
                                {
                                    put("field", "last_clicked");
                                    put("value", "01/02/2015");
                                    put("operator", "gt");
                                    put("and_or", "and");
                                }
                            },
                            new HashMap<String, Object>() {
                                {
                                    put("field", "clicks.campaign_identifier");
                                    put("value", "513");
                                    put("operator", "eq");
                                    put("and_or", "or");
                                }
                            }));
                    put("recipient_count", 1234);
                }
            }).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/contactdb/segments", host)
	request.Method = "POST"
	request.Body = []byte(`{
  "name": "Last Name Miller",
  "list_id": 4,
  "conditions": [
    {
      "field": "last_name",
      "value": "Miller",
      "operator": "eq",
      "and_or": ""
    },
    {
      "field": "last_clicked",
      "value": "01/02/2015",
      "operator": "gt",
      "and_or": "and"
    },
    {
      "field": "clicks.campaign_identifier",
      "value": "513",
      "operator": "eq",
      "and_or": "or"
    }
  ],
  "recipient_count": 1234
}`)
	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": "Last Name Miller",
    "list_id": 4,
    "conditions": [
        {
            "field": "last_name",
            "value": "Miller",
            "operator": "eq",
            "and_or": ""
        },
        {
            "field": "last_clicked",
            "value": "01/02/2015",
            "operator": "gt",
            "and_or": "and"
        },
        {
            "field": "clicks.campaign_identifier",
            "value": "513",
            "operator": "eq",
            "and_or": "or"
        }
    ],
    "recipient_count": 1234
}');

try {
    $response = $sg->client
        ->contactdb()
        ->segments()
        ->post($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": "Last Name Miller",
  "list_id": 4,
  "conditions": [
    {
      "field": "last_name",
      "value": "Miller",
      "operator": "eq",
      "and_or": ""
    },
    {
      "field": "last_clicked",
      "value": "01/02/2015",
      "operator": "gt",
      "and_or": "and"
    },
    {
      "field": "clicks.campaign_identifier",
      "value": "513",
      "operator": "eq",
      "and_or": "or"
    }
  ],
  "recipient_count": 1234
}')

response = sg.client.contactdb.segments.post(request_body: data)
puts response.status_code
puts response.headers
puts response.body
```

```bash
curl -X POST "https://api.sendgrid.com/v3/contactdb/segments" \
--header "Authorization: Bearer $SENDGRID_API_KEY" \
--header "Content-Type: application/json" \
--data '{"name": "Last Name Miller", "list_id": 4, "conditions": [{"field": "last_name", "value": "Miller", "operator": "eq", "and_or": ""}, {"field": "last_clicked", "value": "01/02/2015", "operator": "gt", "and_or": "and"}, {"field": "clicks.campaign_identifier", "value": "513", "operator": "eq", "and_or": "or"}], "recipient_count": 1234}'
```
