> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://developers.beehiiv.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://developers.beehiiv.com/_mcp/server.

# Create segment

POST https://api.beehiiv.com/v2/publications/{publicationId}/segments
Content-Type: application/json

Create a new segment. **Manual segments** — Use `subscriptions` or `emails` input to create a segment from an explicit list of subscription IDs or email addresses. The segment is processed synchronously and returns with `status: completed`. Net new email addresses will be ignored; create subscriptions using the `Create Subscription` endpoint. **Dynamic segments** — Use `custom_fields` input to create a segment that filters subscribers by custom field values. The segment is processed asynchronously and returns with `status: pending`. Results will be available in the `List Segment Subscribers` endpoint after processing is complete.

Reference: https://developers.beehiiv.com/api-reference/segments/create

## Authentication

- `Authorization` header (bearer token, required) — Bearer authentication of the form `Bearer <token>`, where token is your auth token.

## Request

### Path parameters

- `publicationId` (string, required) — The prefixed ID of the publication object

### Body (application/json)

This endpoint expects an object.

- `name` (string, required) — A unique name for the segment that does not already exist in the publication.
- `input` (SegmentSubscriptionInput, required) — Input for segment creation. Use `subscriptions` or `emails` to create a manual segment from explicit lists, or `custom_fields` to create a dynamic segment filtered by custom field values.

## Response

### 201

Created

- `data` (Segment, required) — The segment object. To expand results, see the results endpoint.

## Errors

### 400 Bad Request Error

Bad Request

- `status` (integer, required)
- `statusText` (string, required)
- `errors` (list of ErrorDetail, required)

### 401 Unauthorized Error

Unauthorized. The API key or OAuth access token is missing, invalid, or expired.

- `status` (integer, required)
- `statusText` (string, required)
- `errors` (list of ErrorDetail, required)

### 404 Not Found Error

Resource Not Found

- `status` (integer, required)
- `statusText` (string, required)
- `errors` (list of ErrorDetail, required)

### 429 Too Many Requests Error

Rate Limit Exceeded

- `status` (integer, required)
- `statusText` (string, required)
- `errors` (list of ErrorDetail, required)

### 500 Internal Server Error

Internal Server Error

- `status` (integer, required)
- `statusText` (string, required)
- `errors` (list of ErrorDetail, required)

## Types

### SegmentSubscriptionInput

Input for segment creation. Use `subscriptions` or `emails` to create a manual segment from explicit lists, or `custom_fields` to create a dynamic segment filtered by custom field values.

- `type`: `subscriptions`
  - `subscriptions` (list of string, required)
- `type`: `emails`
  - `emails` (list of string, required)
- `type`: `custom_fields`
  - `custom_fields` (list of CustomFieldFilter, required)
  - `operator` (enum, optional) — The logical operator used to combine multiple custom field filters. Defaults to `and` if not specified.
    - Allowed values: `and`, `or`

### Segment

The segment object. To expand results, see the results endpoint.

- `id` (string, required) — The prefixed ID of the segment.
- `name` (string, required) — The name of the segment.
- `type` (enum, required, default: all) — The type of segment.`dynamic` - The segment is recalculated at set intervals.`static` - The segment is calculated once at creation.`manual` - The segment is not calculated at all. The results are created via CSV.
  - Allowed values: `dynamic`, `static`, `manual`, `all`
- `total_results` (integer, required) — The total number of subscriptions that belong in the segment from the last calculation.
- `status` (enum, required) — The status of the segment's most recent calculation.`pending` - The segment has not been calculated yet.`processing` - The calculation is in progress, and has not completed.`completed` - The calculation was successful.`failed` - Something went wrong during the calculation.
  - Allowed values: `pending`, `processing`, `completed`, `failed`
- `active` (boolean, required) — Dynamic segments are marked inactive if they haven't been used in a specific period of time. Inactive segments will not automatically be recalculated.
- `last_calculated` (integer, optional) — The time the Segment was last calculated. Measured in seconds since the Unix epoch
- `stats` (SegmentStats, optional)

### ErrorDetail

- `message` (string, required)
- `code` (string, required)

### CustomFieldFilter

A single custom field filter condition.

- `name` (string, required) — The display name of the custom field (case-insensitive match). Must be an existing custom field on the publication.
- `operator` (string, required) — The comparison operator for the filter (e.g., `equal`, `not_equal`, `contains`, `exists`, `does_not_exist`). Available operators depend on the custom field's type.
- `value` (string, optional) — The value to compare against. Required for all operators except `exists` and `does_not_exist`.

### SegmentStats

- `open_rate` (double, required) — The average open rate of the subscribers in the segment.
- `total_sent` (integer, required) — The total number of emails sent to the subscribers in the segment.
- `percentage_premium_subscribers` (double, required) — The percentage of subscribers in this segment who are premium in any tier.
- `percentage_subscribers_with_referrals` (double, required) — The percentage of subscribers in this segment who have referred at least one other subscriber.
- `unique_emails_clicked` (integer, required) — The total number of unique emails clicked by subscribers in the segment.
- `total_delivered` (integer, required) — The total number of emails delivered to subscribers in the segment.
- `total_referrals` (integer, required) — The total number of referrals from subscribers in the segment.
- `unsubscribed_rate` (double, required) — The percentage of subscribers in this segment who have unsubscribed.
- `total_subscribers` (integer, required) — The total number of subscribers in the segment.
- `clickthrough_rate` (double, required) — The average clickthrough rate of the subscribers in the segment.
- `unsubscribed_count` (integer, required) — The total number of subscribers in the segment who are unsubscribed.
- `unique_emails_opened` (integer, required) — The total number of unique emails opened by subscribers in the segment.
- `premium_subscribers` (integer, required) — The total number of premium subscribers in the segment.
- `average_referrals_per_subscriber` (double, required) — The average number of referrals per subscriber in the segment.

## Examples

### Create from subscription IDs

**Request**

```json
{
  "name": "My Segment",
  "input": {
    "type": "subscriptions",
    "subscriptions": [
      "sub_00000000-0000-0000-0000-000000000000",
      "sub_00000000-1111-1111-1111-111111111111"
    ]
  }
}
```

**Response**

```json
{
  "data": {
    "id": "seg_00000000-0000-0000-0000-000000000000",
    "name": "My Segment",
    "type": "manual",
    "total_results": 2,
    "status": "completed",
    "active": true,
    "last_calculated": 1666800076
  }
}
```

**SDK Code**

```python Create from subscription IDs
import requests

url = "https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments"

payload = {
    "name": "My Segment",
    "input": {
        "type": "subscriptions",
        "subscriptions": ["sub_00000000-0000-0000-0000-000000000000", "sub_00000000-1111-1111-1111-111111111111"]
    }
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript Create from subscription IDs
const url = 'https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"name":"My Segment","input":{"type":"subscriptions","subscriptions":["sub_00000000-0000-0000-0000-000000000000","sub_00000000-1111-1111-1111-111111111111"]}}'
};

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

```go Create from subscription IDs
package main

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

func main() {

	url := "https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments"

	payload := strings.NewReader("{\n  \"name\": \"My Segment\",\n  \"input\": {\n    \"type\": \"subscriptions\",\n    \"subscriptions\": [\n      \"sub_00000000-0000-0000-0000-000000000000\",\n      \"sub_00000000-1111-1111-1111-111111111111\"\n    ]\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

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

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

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

}
```

```ruby Create from subscription IDs
require 'uri'
require 'net/http'

url = URI("https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments")

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

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"name\": \"My Segment\",\n  \"input\": {\n    \"type\": \"subscriptions\",\n    \"subscriptions\": [\n      \"sub_00000000-0000-0000-0000-000000000000\",\n      \"sub_00000000-1111-1111-1111-111111111111\"\n    ]\n  }\n}"

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

```java Create from subscription IDs
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"name\": \"My Segment\",\n  \"input\": {\n    \"type\": \"subscriptions\",\n    \"subscriptions\": [\n      \"sub_00000000-0000-0000-0000-000000000000\",\n      \"sub_00000000-1111-1111-1111-111111111111\"\n    ]\n  }\n}")
  .asString();
```

```php Create from subscription IDs
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments', [
  'body' => '{
  "name": "My Segment",
  "input": {
    "type": "subscriptions",
    "subscriptions": [
      "sub_00000000-0000-0000-0000-000000000000",
      "sub_00000000-1111-1111-1111-111111111111"
    ]
  }
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp Create from subscription IDs
using RestSharp;

var client = new RestClient("https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"name\": \"My Segment\",\n  \"input\": {\n    \"type\": \"subscriptions\",\n    \"subscriptions\": [\n      \"sub_00000000-0000-0000-0000-000000000000\",\n      \"sub_00000000-1111-1111-1111-111111111111\"\n    ]\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Create from subscription IDs
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "name": "My Segment",
  "input": [
    "type": "subscriptions",
    "subscriptions": ["sub_00000000-0000-0000-0000-000000000000", "sub_00000000-1111-1111-1111-111111111111"]
  ]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

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()
```

### Create from custom field filters

**Request**

```json
{
  "name": "Newsletter X Subscribers",
  "input": {
    "type": "custom_fields",
    "custom_fields": [
      {
        "name": "Newsletter X",
        "operator": "equal",
        "value": "true"
      }
    ],
    "operator": "and"
  }
}
```

**Response**

```json
{
  "data": {
    "id": "seg_00000000-0000-0000-0000-000000000000",
    "name": "Newsletter X Subscribers",
    "type": "dynamic",
    "total_results": 0,
    "status": "pending",
    "active": true
  }
}
```

**SDK Code**

```python Create from custom field filters
import requests

url = "https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments"

payload = {
    "name": "Newsletter X Subscribers",
    "input": {
        "type": "custom_fields",
        "custom_fields": [
            {
                "name": "Newsletter X",
                "operator": "equal",
                "value": "true"
            }
        ],
        "operator": "and"
    }
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript Create from custom field filters
const url = 'https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"name":"Newsletter X Subscribers","input":{"type":"custom_fields","custom_fields":[{"name":"Newsletter X","operator":"equal","value":"true"}],"operator":"and"}}'
};

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

```go Create from custom field filters
package main

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

func main() {

	url := "https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments"

	payload := strings.NewReader("{\n  \"name\": \"Newsletter X Subscribers\",\n  \"input\": {\n    \"type\": \"custom_fields\",\n    \"custom_fields\": [\n      {\n        \"name\": \"Newsletter X\",\n        \"operator\": \"equal\",\n        \"value\": \"true\"\n      }\n    ],\n    \"operator\": \"and\"\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

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

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

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

}
```

```ruby Create from custom field filters
require 'uri'
require 'net/http'

url = URI("https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments")

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

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"name\": \"Newsletter X Subscribers\",\n  \"input\": {\n    \"type\": \"custom_fields\",\n    \"custom_fields\": [\n      {\n        \"name\": \"Newsletter X\",\n        \"operator\": \"equal\",\n        \"value\": \"true\"\n      }\n    ],\n    \"operator\": \"and\"\n  }\n}"

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

```java Create from custom field filters
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"name\": \"Newsletter X Subscribers\",\n  \"input\": {\n    \"type\": \"custom_fields\",\n    \"custom_fields\": [\n      {\n        \"name\": \"Newsletter X\",\n        \"operator\": \"equal\",\n        \"value\": \"true\"\n      }\n    ],\n    \"operator\": \"and\"\n  }\n}")
  .asString();
```

```php Create from custom field filters
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments', [
  'body' => '{
  "name": "Newsletter X Subscribers",
  "input": {
    "type": "custom_fields",
    "custom_fields": [
      {
        "name": "Newsletter X",
        "operator": "equal",
        "value": "true"
      }
    ],
    "operator": "and"
  }
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp Create from custom field filters
using RestSharp;

var client = new RestClient("https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"name\": \"Newsletter X Subscribers\",\n  \"input\": {\n    \"type\": \"custom_fields\",\n    \"custom_fields\": [\n      {\n        \"name\": \"Newsletter X\",\n        \"operator\": \"equal\",\n        \"value\": \"true\"\n      }\n    ],\n    \"operator\": \"and\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Create from custom field filters
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "name": "Newsletter X Subscribers",
  "input": [
    "type": "custom_fields",
    "custom_fields": [
      [
        "name": "Newsletter X",
        "operator": "equal",
        "value": "true"
      ]
    ],
    "operator": "and"
  ]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/segments")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

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()
```