0

Create Record

by
Published 4 days ago

Insert a record into any table (incident, change_request, sys_user, cmdb_ci, or a custom table). Pick the table from a live dropdown and pass a column/value map.

Script servicenow Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 5 days ago
1
//native
2

3
export type DynSelect_table = string
4

5
function authHeader(auth: RT.Servicenow) {
6
  return auth.token
7
    ? `Bearer ${auth.token}`
8
    : `Basic ${btoa(`${auth.username}:${auth.password}`)}`
9
}
10

11
// Dropdown of the instance's tables (sys_db_object).
12
export async function table(auth: RT.Servicenow) {
13
  const response = await fetch(
14
    `${auth.instance_url}/api/now/table/sys_db_object?sysparm_fields=name,label&sysparm_limit=10000`,
15
    {
16
      headers: {
17
        Authorization: authHeader(auth),
18
        Accept: "application/json",
19
      },
20
    }
21
  )
22
  if (!response.ok) {
23
    throw new Error(`${response.status} ${await response.text()}`)
24
  }
25
  const { result } = (await response.json()) as {
26
    result: { name: string; label: string }[]
27
  }
28
  return result
29
    .filter((t) => t.name)
30
    .map((t) => ({ value: t.name, label: `${t.label} (${t.name})` }))
31
    .sort((a, b) => a.label.localeCompare(b.label))
32
}
33

34
/**
35
 * Create Record
36
 * Insert a record into any table (incident, change_request, sys_user, cmdb_ci, or a custom table). Pick the table from a live dropdown and pass a column/value map.
37
 */
38
export async function main(
39
  auth: RT.Servicenow,
40
  table: DynSelect_table,
41
  body: { [key: string]: any }
42
) {
43
  const url = new URL(`${auth.instance_url}/api/now/table/${table}`)
44

45
  const response = await fetch(url, {
46
    method: "POST",
47
    headers: {
48
      Authorization: authHeader(auth),
49
      "Content-Type": "application/json",
50
      Accept: "application/json",
51
    },
52
    body: JSON.stringify(body),
53
  })
54

55
  if (!response.ok) {
56
    throw new Error(`${response.status} ${await response.text()}`)
57
  }
58

59
  return await response.json()
60
}
61