0

Batch Upsert CRM Objects

by
Published today

Create or update up to 100 CRM records of one object type, matched on a unique property.

Script hubspot Verified

The script

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

3
export type DynSelect_object_type = string
4

5
// Dropdown of the standard CRM object types plus the account's custom objects.
6
export async function object_type(auth: RT.Hubspot) {
7
  const standard = [
8
    "contacts",
9
    "companies",
10
    "deals",
11
    "tickets",
12
    "line_items",
13
    "products",
14
    "quotes",
15
    "leads",
16
    "notes",
17
    "tasks",
18
    "meetings",
19
    "calls",
20
    "emails",
21
    "communications",
22
  ].map((o) => ({ value: o, label: o }))
23
  const response = await fetch("https://api.hubapi.com/crm/v3/schemas", {
24
    headers: {
25
      Authorization: `Bearer ${auth.token}`,
26
      Accept: "application/json",
27
    },
28
  })
29
  // A token without crm.schemas.custom.read still gets the standard objects.
30
  if (!response.ok) return standard
31
  const { results } = (await response.json()) as {
32
    results: { fullyQualifiedName: string; labels: { plural: string } }[]
33
  }
34
  return [
35
    ...standard,
36
    ...results.map((s) => ({
37
      value: s.fullyQualifiedName,
38
      label: `${s.labels.plural} (custom)`,
39
    })),
40
  ]
41
}
42

43
/**
44
 * Batch Upsert CRM Objects
45
 * Create or update up to 100 CRM records of one object type, matched on a unique property. `id_property` is that property's name (email for contacts, or a custom property with unique values) and each input's `id` is the value of that property. Object types other than contacts, companies and deals need their own scope on the connection (e.g. tickets, crm.objects.line_items.read, crm.objects.custom.read).
46
 */
47
export async function main(
48
  auth: RT.Hubspot,
49
  object_type: DynSelect_object_type,
50
  id_property: string,
51
  inputs: { id: string; properties: { [key: string]: any } }[]
52
) {
53
  const response = await fetch(
54
    `https://api.hubapi.com/crm/v3/objects/${object_type}/batch/upsert`,
55
    {
56
      method: "POST",
57
      headers: {
58
        Authorization: `Bearer ${auth.token}`,
59
        "Content-Type": "application/json",
60
        Accept: "application/json",
61
      },
62
      body: JSON.stringify({
63
        inputs: inputs.map((input) => ({ ...input, idProperty: id_property })),
64
      }),
65
    }
66
  )
67

68
  if (!response.ok) {
69
    throw new Error(`${response.status} ${await response.text()}`)
70
  }
71

72
  return await response.json()
73
}
74