0

Create incident

by
Published today

Open an incident with short description, impact, urgency, CI, assignment group and caller. ServiceNow computes the priority from impact and urgency. Returns sys_id and number.

Script servicenow Verified

The script

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

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

9
/**
10
 * Create Incident
11
 * Open an incident (Table API, POST /api/now/table/incident). Set impact and urgency (default choices 1 = High, 2 = Medium, 3 = Low): ServiceNow computes the priority from them, so priority is not an input. Reference fields (cmdb_ci, assignment_group, caller) take sys_ids. Returns sys_id, number, priority and the full record.
12
 */
13
export async function main(
14
  auth: RT.Servicenow,
15
  short_description: string,
16
  description: string | undefined,
17
  impact: string | undefined,
18
  urgency: string | undefined,
19
  cmdb_ci: string | undefined,
20
  assignment_group: string | undefined,
21
  caller: string | undefined,
22
  fields: { [key: string]: any } | undefined
23
) {
24
  const url = new URL(`${auth.instance_url}/api/now/table/incident`)
25

26
  const body: { [key: string]: any } = { ...(fields ?? {}) }
27
  const values: { [key: string]: string | undefined } = {
28
    short_description,
29
    description,
30
    impact,
31
    urgency,
32
    cmdb_ci,
33
    assignment_group,
34
    caller_id: caller,
35
  }
36
  for (const [key, v] of Object.entries(values)) {
37
    if (v != null && v !== "") body[key] = v
38
  }
39

40
  const response = await fetch(url, {
41
    method: "POST",
42
    headers: {
43
      Authorization: authHeader(auth),
44
      "Content-Type": "application/json",
45
      Accept: "application/json",
46
    },
47
    body: JSON.stringify(body),
48
  })
49

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

54
  const { result } = (await response.json()) as { result: any }
55
  return {
56
    sys_id: result.sys_id,
57
    number: result.number,
58
    priority: result.priority,
59
    record: result,
60
  }
61
}
62