Using PHP with JSON and ServiceNowa

Performing web service interaction in ServiceNow with JSON is becoming a more popular discussion point among customers and partners alike. I decided to draw up a PHP implementation of performing Inserts, Updates, Queries, and Deletions of ServiceNow records via the JSON web service interface.

Please note, in order for you to utilize JSON web services with ServiceNow, you will need to enable the appropriate plugin. Please refer to the official documentation for JSON Web Services on the ServiceNow wiki.

Essentially the JSON interface utilizes a combination of URLs and POST data to perform the interaction with ServiceNow. All authentication is done via Basic Authentication.

cURL has an easy set of libraries and tools that allow us to perform these operations.

First we use cURL to prepare an HTTP POST to our URL using the following syntax:

1
2
$query = "https://myinstance.service-now.com/incident.do?JSON&sysparm_action=insert";
$curl = curl_init($query);

The above snippet initialized cURL to be prepared to visit the incident table using a JSON processor. The sysparm_action parameter tells the web service what type of operation we want to perform. In this case it is “insert”. See the documentation for all available actions.

In order to authenticate into the instance in your HTTP Request you will use the following syntax (assume your username is “John” and your password is “SecurePass”:

1
2
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "John:SecurePass");

Some requests require a JSON formatted query string to be send with your posted request. The “insert” operation does require JSON string that provides the fields and corresponding values that you will be setting in your new record. You set this up similar to the following snippet:

1
2
3
4
$jsonInput = '{"short_description":"My First JSON incident","priority":"1"}';
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonInput);

That code tells cURL to send a POST request sending the specific JSON body. In this example, the JSON string indicates that we will create an incident with a short_description and priority.

You then send the request by using something like the following:

1
2
$response = curl_exec($curl);
curl_close($curl);

That sends the request, stores the response into a variable, and closes the connection. You can then convert the resulting JSON string in the response variable to a PHP object doing the following:

1
$json = json_decode($response);

Since there are several different actions available, and each action is a bit different, I created a script that provides you a sample of using all of the available JSON Web Service actions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php

//Setup
$instance = "demo";
$username = "admin";
$password = "admin";
$table = "cmdb_ci_database";
$printFields = array("sys_id", "name", "type", "version");

//Create a MySQL Database Server
echo "<br><br>Create a MySQL Database Server<br>";
$filter = "";
$json = '{"name":"MySQL DB #3","type":"MySQL","version":"1.0.0"}';
$res = jsonQuery($instance, $username, $password, $table, "insert", $filter, $json);
$newDbServer = $res->records[0]->sys_id;
printRecord($res, $printFields);

//Get the newly created MySQL Server
echo "<br><br>Get the newly created MySQL Server<br>";
$filter = "";
$json = '{"sysparm_sys_id":"'.$newDbServer.'"}';
$res = jsonQuery($instance, $username, $password, $table, "get", $filter, $json);
printRecord($res, $printFields);

// Update newly created MySQL Server
echo "<br><br>Update newly created MySQL Server<br>";
$filter = "sys_id%3D$newDbServer";
$json = '{"version":"2.0.0"}';
$res = jsonQuery($instance, $username, $password, $table, "update", $filter, $json);
printRecord($res, $printFields);

// Delete newly created MySQL Server
echo "<br><br>Delete newly created MySQL Server<br>";
$filter = "";
$json = "{"sysparm_sys_id":"$newDbServer"}";
$res = jsonQuery($instance, $username, $password, $table, "deleteRecord", $filter, $json);
printRecord($res, $printFields);

//Insert Multiple MySQL Server Records
echo "<br><br>Insert Multiple MySQL Server Records<br>";
$filter = "";
$json = '{"records":[{"name":"MySQL DB #3","type":"MySQL","version":"1.0.0"},'.
                          '{"name":"MySQL DB #3","type":"MySQL","version":"1.2.0"}]}';
$res = jsonQuery($instance, $username, $password, $table, "insert", $filter, $json);
$newDbServer = $res->records[0]->sys_id;
printRecord($res, $printFields);

//getKeys of all MySQL Records that have the name: MySQL DB #3
echo "<br><br>getKeys of all MySQL Records that have the name: MySQL DB #3<br>";
$filter = "name%3DMySQL%20DB%20%233";
$json = "";
$res = jsonQuery($instance, $username, $password, $table, "getKeys", $filter, $json);
//printRecord($res, $printFields);
foreach($res->records as $key) echo "[sys_id]: $key<BR>";

// Delete all MySQL Servers with this name: MySQL DB #3
echo "<br><br>Delete all MySQL Servers with this name: MySQL DB #3<br>";
$filter = "name%3DMySQL%20DB%20%233";
$json = "";
$res = jsonQuery($instance, $username, $password, $table, "deleteMultiple", $filter, $json);
printRecord($res, $printFields);

// List MySQL Databases
echo "<br><br>List current MySQL Databases<br>";
$filter = "type%3DMySQL";
$json = "";
$res = jsonQuery($instance, $username, $password, $table, "getRecords", $filter, $json);
printRecord($res, $printFields);




function jsonQuery($instance, $username, $password, $table, $action, $encodedQuery, $jsonInput){
  $query = "https://$instance.service-now.com/$table.do?JSON&" .
          "sysparm_action=$action";
  if($encodedQuery) $query .= "&sysparm_query=$encodedQuery";
  $curl = curl_init($query);
 
  curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
  curl_setopt($curl, CURLOPT_VERBOSE, 1);
  curl_setopt($curl, CURLOPT_HEADER, false);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
 
  if( $jsonInput ){
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
    curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonInput);
  }
 
  $response = curl_exec($curl);
  curl_close($curl);
  $json = json_decode($response);
  if ($json != "" && property_exists($json, 'error')){
    throw new ErrorException("SN JSON Error: {$json->error}");
  }
  return $json;
}

function printRecord($obj, $fields){
  if(!obj || !$obj->records) return;
  foreach($obj->records as $rec){
    foreach($rec as $key => $value){
      if( in_array($key, $fields ) ) echo "[$key]: $value; ";
    }
    echo "<BR>";
  }
}
?>

Running this script provides an output similar to the following screen shot:

PHP Script Output for JSON Web Service Test with ServiceNow