0

Add Contact to List

by
Published today

Add one or more contacts (record IDs) to a list.

Script hubspot Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 4 hours ago
1
//native
2

3
export type DynSelect_list_id = string
4

5
// Dropdown of the account's lists.
6
export async function list_id(auth: RT.Hubspot) {
7
  const response = await fetch("https://api.hubapi.com/crm/v3/lists/search", {
8
    method: "POST",
9
    headers: {
10
      Authorization: `Bearer ${auth.token}`,
11
      "Content-Type": "application/json",
12
      Accept: "application/json",
13
    },
14
    body: JSON.stringify({ count: 500 }),
15
  })
16
  if (!response.ok) {
17
    throw new Error(`${response.status} ${await response.text()}`)
18
  }
19
  const { lists } = (await response.json()) as {
20
    lists: { listId: string; name: string; processingType: string }[]
21
  }
22
  return lists.map((l) => ({
23
    value: l.listId,
24
    label: `${l.name} (${l.processingType})`,
25
  }))
26
}
27

28
/**
29
 * Add Contact to List
30
 * Add one or more contacts (record IDs) to a list. Only MANUAL and SNAPSHOT lists accept manual additions; DYNAMIC lists are filled by their filters. Requires crm.lists.write.
31
 */
32
export async function main(
33
  auth: RT.Hubspot,
34
  list_id: DynSelect_list_id,
35
  contact_ids: string[]
36
) {
37
  const url = new URL(
38
    `https://api.hubapi.com/crm/v3/lists/${list_id}/memberships/add`
39
  )
40

41
  const response = await fetch(url, {
42
    method: "PUT",
43
    headers: {
44
      Authorization: `Bearer ${auth.token}`,
45
      "Content-Type": "application/json",
46
      Accept: "application/json",
47
    },
48
    body: JSON.stringify(contact_ids),
49
  })
50

51
  if (!response.ok) {
52
    throw new Error(`${response.status} ${await response.text()}`)
53
  }
54

55
  return await response.json()
56
}
57