0

Get Profiles for Segment

by
Published Apr 8, 2025

Get all profiles within a segment with the given segment ID. Filter to request a subset of all profiles. Profiles can be filtered by `email`, `phone_number`, `push_token`, and `joined_group_at` fields. Profiles can be sorted by the following fields, in ascending and descending order: `joined_group_at`*Rate limits*:Burst: `75/s`Steady: `700/m` **Scopes:** `profiles:read` `segments:read`

Script klaviyo Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Klaviyo = {
3
  apiKey: string;
4
};
5
/**
6
 * Get Profiles for Segment
7
 * Get all profiles within a segment with the given segment ID.
8

9
Filter to request a subset of all profiles. Profiles can be filtered by `email`, `phone_number`, `push_token`, and `joined_group_at` fields. Profiles can be sorted by the following fields, in ascending and descending order: `joined_group_at`*Rate limits*:Burst: `75/s`Steady: `700/m`
10

11
 */
12
export async function main(
13
  auth: Klaviyo,
14
  id: string,
15
  additional_fields_profile_: string | undefined,
16
  fields_profile_: string | undefined,
17
  filter: string | undefined,
18
  page_cursor_: string | undefined,
19
  page_size_: string | undefined,
20
  sort: "joined_group_at" | "-joined_group_at" | undefined,
21
  revision: string,
22
) {
23
  const url = new URL(`https://a.klaviyo.com/api/segments/${id}/profiles`);
24
  for (const [k, v] of [
25
    ["additional-fields[profile]", additional_fields_profile_],
26
    ["fields[profile]", fields_profile_],
27
    ["filter", filter],
28
    ["page[cursor]", page_cursor_],
29
    ["page[size]", page_size_],
30
    ["sort", sort],
31
  ]) {
32
    if (v !== undefined && v !== "" && k !== undefined) {
33
      url.searchParams.append(k, v);
34
    }
35
  }
36
  const response = await fetch(url, {
37
    method: "GET",
38
    headers: {
39
      revision: revision,
40
      "Accept": "application/vnd.api+json",
41
      Authorization: "Klaviyo-API-Key " + auth.apiKey,
42
    },
43
    body: undefined,
44
  });
45
  if (!response.ok) {
46
    const text = await response.text();
47
    throw new Error(`${response.status} ${text}`);
48
  }
49
  return await response.json();
50
}
51