# Query an audience without saving it

Source: https://jointextkit.com/docs/api/segments/query-audience
Index: https://jointextkit.com/llms.txt

`POST /v1/segments/preview`

Runs a rule list now and answers with the counts `GET /segments/{id}/preview` gives plus the first `limit` matching contacts. Use it to ask cohort questions (who replied in the last 7 days, who got a batch and did not reply, who did one event and not another) before saving the rules as a segment to page through or send to. `eligible + opted_out + topic_unsubscribed = matched`.

Send your API key as a bearer token: `Authorization: Bearer ssms_sk_...`. Test keys run this endpoint against the [sandbox](/docs/sandbox); see [Authentication](/docs/authentication) for key modes and scopes.

## Request body

JSON (`Content-Type: application/json`).

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `match` | `all`, `any` | No | Default "all". |
| `rules` | array of SegmentRule | No | At most 10 items. |
| `topic_id` | string | No | Topic id or name: eligible also removes contacts unsubscribed from it |
| `limit` | integer | No | How many matching contacts to return Default 25. Maximum 100. Minimum 0. |

## Responses

| Status | Meaning | Body |
| --- | --- | --- |
| 200 | Counts and the first contacts | JSON object |
| 400 | Invalid rules | `Error` |
| 401 | Missing, malformed, or revoked API key | `Error` |
| 402 | Billable live calls only: the prepaid credit balance cannot cover the call (insufficient_credits); nothing was done or charged | `Error` |
| 429 | Rate limit or quota exceeded | `Error` |

### 200: response fields

| Field | Type | Description |
| --- | --- | --- |
| `object` | `segment_preview` |  |
| `segment_id` | string | Nullable. |
| `topic_id` | string | Nullable. |
| `contacts_total` | integer |  |
| `matched` | integer |  |
| `opted_out` | integer |  |
| `topic_unsubscribed` | integer |  |
| `eligible` | integer |  |
| `contacts` | array of Contact |  |

## Errors

| Status | When |
| --- | --- |
| 400 | Invalid rules |
| 401 | Missing, malformed, or revoked API key |
| 402 | Billable live calls only: the prepaid credit balance cannot cover the call (insufficient_credits); nothing was done or charged |
| 429 | Rate limit or quota exceeded |

Every error has the same JSON shape, and `request_id` matches the `X-Request-Id` response header. [Errors](/docs/errors) lists every code and what to do about it.

```json
{
  "error": {
    "code": "invalid_request",
    "message": "What went wrong, in plain words.",
    "param": "the_field",
    "request_id": "req_a1B2c3D4e5F6g7H8"
  }
}
```

## Examples

### Node.js

The Node.js SDK does not wrap this endpoint yet; call it over HTTP.

```javascript
const res = await fetch('https://api.jointextkit.com/v1/segments/preview', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.TEXTKIT_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "rules": [
      {
        "field": "last_reply_at",
        "op": "after",
        "value": "7d"
      },
      {
        "field": "tag",
        "op": "is",
        "value": "vip"
      }
    ]
  }),
});

if (!res.ok) throw new Error((await res.json()).error.message);
const data = await res.json();
```

### PHP

```php
<?php

$ch = curl_init('https://api.jointextkit.com/v1/segments/preview');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('TEXTKIT_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'rules' => [
            [
                'field' => 'last_reply_at',
                'op' => 'after',
                'value' => '7d',
            ],
            [
                'field' => 'tag',
                'op' => 'is',
                'value' => 'vip',
            ],
        ],
    ]),
]);

$data = json_decode(curl_exec($ch), true);
```

### Python

The Python SDK does not wrap this endpoint yet; call it over HTTP.

```python
import json, os, urllib.request

req = urllib.request.Request(
    "https://api.jointextkit.com/v1/segments/preview",
    method="POST",
    headers={
        "Authorization": f"Bearer {os.environ['TEXTKIT_API_KEY']}",
        "Content-Type": "application/json",
    },
    data=json.dumps({
        "rules": [
            {
                "field": "last_reply_at",
                "op": "after",
                "value": "7d"
            },
            {
                "field": "tag",
                "op": "is",
                "value": "vip"
            }
        ]
    }).encode(),
)
with urllib.request.urlopen(req) as res:
    data = json.load(res)
```

### Ruby

```ruby
require "net/http"
require "json"

uri = URI("https://api.jointextkit.com/v1/segments/preview")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{ENV["TEXTKIT_API_KEY"]}"
req["Content-Type"] = "application/json"
req.body = {
  "rules": [
    {
      "field": "last_reply_at",
      "op": "after",
      "value": "7d"
    },
    {
      "field": "tag",
      "op": "is",
      "value": "vip"
    }
  ]
}.to_json

res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }
data = JSON.parse(res.body)
```

### Go

```go
package main

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

func main() {
	body := strings.NewReader(`{
	  "rules": [
	    {
	      "field": "last_reply_at",
	      "op": "after",
	      "value": "7d"
	    },
	    {
	      "field": "tag",
	      "op": "is",
	      "value": "vip"
	    }
	  ]
	}`)
	req, _ := http.NewRequest("POST", "https://api.jointextkit.com/v1/segments/preview", body)
	req.Header.Set("Authorization", "Bearer "+os.Getenv("TEXTKIT_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	data, _ := io.ReadAll(res.Body)
	fmt.Println(res.Status, string(data))
}
```

### Rust

```rust
// cargo add reqwest --features blocking,json
// cargo add serde_json
use serde_json::json;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key = std::env::var("TEXTKIT_API_KEY")?;
    let res = reqwest::blocking::Client::new()
        .post("https://api.jointextkit.com/v1/segments/preview")
        .bearer_auth(key)
        .json(&json!({
          "rules": [
            {
              "field": "last_reply_at",
              "op": "after",
              "value": "7d"
            },
            {
              "field": "tag",
              "op": "is",
              "value": "vip"
            }
          ]
        }))
        .send()?
        .error_for_status()?;
    let data: serde_json::Value = res.json()?;
    println!("{data}");
    Ok(())
}
```

### Java

```java
import java.net.URI;
import java.net.http.*;

public class Main {
    public static void main(String[] args) throws Exception {
        var request = HttpRequest.newBuilder(URI.create("https://api.jointextkit.com/v1/segments/preview"))
            .header("Authorization", "Bearer " + System.getenv("TEXTKIT_API_KEY"))
            .header("Content-Type", "application/json")
            .method("POST", HttpRequest.BodyPublishers.ofString("""
                {
                  "rules": [
                    {
                      "field": "last_reply_at",
                      "op": "after",
                      "value": "7d"
                    },
                    {
                      "field": "tag",
                      "op": "is",
                      "value": "vip"
                    }
                  ]
                }
                """))
            .build();

        var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode() + " " + response.body());
    }
}
```

### .NET

```csharp
using System.Net.Http.Headers;
using System.Text;

var http = new HttpClient();
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    "Bearer", Environment.GetEnvironmentVariable("TEXTKIT_API_KEY"));

var body = new StringContent("""
    {
      "rules": [
        {
          "field": "last_reply_at",
          "op": "after",
          "value": "7d"
        },
        {
          "field": "tag",
          "op": "is",
          "value": "vip"
        }
      ]
    }
    """, Encoding.UTF8, "application/json");
var res = await http.PostAsync("https://api.jointextkit.com/v1/segments/preview", body);
res.EnsureSuccessStatusCode();

var data = await res.Content.ReadAsStringAsync();
```

### cURL

```bash
curl -X POST "https://api.jointextkit.com/v1/segments/preview" \
  -H "Authorization: Bearer $TEXTKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "rules": [
    {
      "field": "last_reply_at",
      "op": "after",
      "value": "7d"
    },
    {
      "field": "tag",
      "op": "is",
      "value": "vip"
    }
  ]
}'
```

## Related

- Guide: [Contacts](/docs/contacts)
- [All segments endpoints](/docs/api#segments)
- [API reference](/docs/api)
