REST API ExplorerのコードサンプルでServiceNowインスタンスにHTTP Request(POST)を飛ばしてIncidentを起票する

Version: Kingston

こちらのドキュメントによると(Version: London)

https://docs.servicenow.com/bundle/london-application-development/page/integrate/web-services/reference/r_AvailableWebServices.html

ServiceNowは「HTTP ベースの Web サービスにより、多様なアプリケーション間でのやり取りが可能になります。ServiceNow は、受信 (プロバイダー) と送信 (コンシューマー) の両方の Web サービスをサポートしています。」だそうです本記事ではREST APIを試してみたいと思います

# 作るもの

bashでServiceNowインスタンスにHTTP Request(POST)を飛ばして

```
[root@cfebb9fa5330 zabbix]# cd /usr/lib/zabbix/alertscripts
[root@cfebb9fa5330 alertscripts]# vi aaa.sh
#!/bin/bash

curl "https://********.service-now.com/api/now/table/incident" \
--request POST \
--header "Accept:application/json" \
--header "Content-Type:application/json" \
--data "{\"short_description\":\"can you explain difference between rice bowl and rice ball\"}" \
--user 'admin':'********'
:wq!
[root@cfebb9fa5330 alertscripts]# chmod 755 aaa.sh
[root@cfebb9fa5330 alertscripts]# ./aaa.sh
{"result":{"parent":"","made_sla":"true","caused_by":"","watch_list":"","upon_reject":"cancel","sys_updated_on":"2018-07-01 06:15:38","child_incidents":"0","hold_reason":"","approval_history":"","skills":"","number":"INC0010131","resolved_by":"","sys_updated_by":"admin","opened_by":{"link":"https://********.service-now.com/api/now/table/sys_user/6816f79cc0a8016401c5a33be04be441","value":"6816f79cc0a8016401c5a33be04be441"},"user_input":"","sys_created_on":"2018-07-01 06:15:38","sys_domain":{"link":"https://********.service-now.com/api/now/table/domain/09ff3d105f231000b12e3572f2b4775d","value":"09ff3d105f231000b12e3572f2b4775d"},"state":"1","task_for":"","sys_created_by":"admin","knowledge":"false","order":"","calendar_stc":"","closed_at":"","u_work_notes":"","cmdb_ci":"","delivery_plan":"","contract":"","impact":"3","active":"true","work_notes_list":"","business_service":"","priority":"5","sys_domain_path":"!!!/!!#/!!!/","rfc":"","time_worked":"","expected_start":"","opened_at":"2018-07-01 06:15:38","business_duration":"","group_list":"","work_end":"","caller_id":"","reopened_time":"","resolved_at":"","approval_set":"","subcategory":"","work_notes":"","short_description":"can you explain difference between rice bowl and rice ball","close_code":"","correlation_display":"","delivery_task":"","work_start":"","assignment_group":"","additional_assignee_list":"","business_stc":"","description":"","calendar_duration":"","close_notes":"","notify":"1","sys_class_name":"incident","closed_by":"","follow_up":"","parent_incident":"","sys_id":"3df6a51d4f031300bac28020a310c7ee","contact_type":"","reopened_by":"","incident_state":"1","urgency":"3","problem_id":"","company":"","reassignment_count":"0","activity_due":"","assigned_to":"","severity":"3","comments":"","approval":"not requested","sla_due":"","comments_and_work_notes":"","due_date":"","sys_mod_count":"0","reopen_count":"0","sys_tags":"","escalation":"0","upon_approval":"proceed","correlation_id":"","location":"","category":"inquiry"}}
[root@cfebb9fa5330 alertscripts]#
```

Incidentを起票します

<img width="1035" alt="FireShot Screen Capture #065 - &#x27;Incidents [Metrics view] I Incident Ticket System&#x27; - dev48240_service-now_com_nav_to_do_uri=_incident_list_do_sysparm.png" src="https://qiita-image-store.s3.amazonaws.com/0/193272/edf5871a-fc30-6417-1ba8-8171bac91589.png">

# REST API Explorerを試す
## cURLでPOST
Filter navigatorにrestと入力し[System Web Services] - [▼REST] - [REST API Explorer]を表示します今回はレコードを追加したいので画面の真ん中辺りの"Create a record (POST)"をクリックしますtableNameでIncidentを選択します情報を取得したいときはGET, 編集したいときはPUT, 削除したいときはDELETEなどとHTTP Methodを使い分けるようです

<img width="1035" alt="FireShot Screen Capture #057 - &#x27;REST API Explorer I Incident Ticket System&#x27; - dev48240_service-now_com_nav_to_do_uri=_$restapi_do.png" src="https://qiita-image-store.s3.amazonaws.com/0/193272/0d057350-65d0-56e6-cb6e-65c81ff90161.png">

画面を下にスクロールしてRequest BodyでShort Descriptionを選択して適当なメッセージを入力しますそうするとJSONのBodyが表示されます

![FireShot Screen Capture #062 - 'REST API Explorer I Incident Ticket System' - dev48240_service-now_com_nav_to_do_uri=_$restapi_do.png](https://qiita-image-store.s3.amazonaws.com/0/193272/33ef16b5-ee96-3a9a-1d46-ac38fc1f9e98.png)

[Send]をクリックしてみます201 CreatedでHTTP Request(POST)が成功したようです

<img width="1035" alt="FireShot Screen Capture #063 - &#x27;REST API Explorer I Incident Ticket System&#x27; - dev48240_service-now_com_nav_to_do_uri=_$restapi_do.png" src="https://qiita-image-store.s3.amazonaws.com/0/193272/c7db18d3-9d0b-7ad5-ac04-e3c31d8a97ef.png">

画面を少し上にスクロールするとコードのサンプルがありましたServiceNow Script, cURL, Python, Ruby, JavaScript, Perl, Powershellとあったので試しにcURLをクリックしたところコードサンプルのダイアログが表示されました

<img width="1035" alt="FireShot Screen Capture #064 - &#x27;REST API Explorer I Incident Ticket System&#x27; - dev48240_service-now_com_nav_to_do_uri=_$restapi_do.png" src="https://qiita-image-store.s3.amazonaws.com/0/193272/499861bb-02cc-0457-86fc-5ce1aeb5dfdd.png">

コードをコピーして実行可能な環境でbashにして

```
[root@cfebb9fa5330 zabbix]# cd /usr/lib/zabbix/alertscripts
[root@cfebb9fa5330 alertscripts]# vi aaa.sh
```

編集してペーストして(User ID, Passwordはインスタンスのアカウントの値に合わせて編集します)

```
#!/bin/bash

curl "https://********.service-now.com/api/now/table/incident" \
--request POST \
--header "Accept:application/json" \
--header "Content-Type:application/json" \
--data "{\"short_description\":\"can you explain difference between rice bowl and rice ball\"}" \
--user 'admin':'********'
```

保存して

```
:wq!
```

パーミッションを変更して実行して

```
[root@cfebb9fa5330 alertscripts]# chmod 755 aaa.sh
[root@cfebb9fa5330 alertscripts]# ./aaa.sh
{"result":{"parent":"","made_sla":"true","caused_by":"","watch_list":"","upon_reject":"cancel","sys_updated_on":"2018-07-01 06:15:38","child_incidents":"0","hold_reason":"","approval_history":"","skills":"","number":"INC0010131","resolved_by":"","sys_updated_by":"admin","opened_by":{"link":"https://********.service-now.com/api/now/table/sys_user/6816f79cc0a8016401c5a33be04be441","value":"6816f79cc0a8016401c5a33be04be441"},"user_input":"","sys_created_on":"2018-07-01 06:15:38","sys_domain":{"link":"https://********.service-now.com/api/now/table/domain/09ff3d105f231000b12e3572f2b4775d","value":"09ff3d105f231000b12e3572f2b4775d"},"state":"1","task_for":"","sys_created_by":"admin","knowledge":"false","order":"","calendar_stc":"","closed_at":"","u_work_notes":"","cmdb_ci":"","delivery_plan":"","contract":"","impact":"3","active":"true","work_notes_list":"","business_service":"","priority":"5","sys_domain_path":"!!!/!!#/!!!/","rfc":"","time_worked":"","expected_start":"","opened_at":"2018-07-01 06:15:38","business_duration":"","group_list":"","work_end":"","caller_id":"","reopened_time":"","resolved_at":"","approval_set":"","subcategory":"","work_notes":"","short_description":"can you explain difference between rice bowl and rice ball","close_code":"","correlation_display":"","delivery_task":"","work_start":"","assignment_group":"","additional_assignee_list":"","business_stc":"","description":"","calendar_duration":"","close_notes":"","notify":"1","sys_class_name":"incident","closed_by":"","follow_up":"","parent_incident":"","sys_id":"3df6a51d4f031300bac28020a310c7ee","contact_type":"","reopened_by":"","incident_state":"1","urgency":"3","problem_id":"","company":"","reassignment_count":"0","activity_due":"","assigned_to":"","severity":"3","comments":"","approval":"not requested","sla_due":"","comments_and_work_notes":"","due_date":"","sys_mod_count":"0","reopen_count":"0","sys_tags":"","escalation":"0","upon_approval":"proceed","correlation_id":"","location":"","category":"inquiry"}}
[root@cfebb9fa5330 alertscripts]#
```

Incidentを起票出来ているようです

<img width="1035" alt="FireShot Screen Capture #065 - &#x27;Incidents [Metrics view] I Incident Ticket System&#x27; - dev48240_service-now_com_nav_to_do_uri=_incident_list_do_sysparm.png" src="https://qiita-image-store.s3.amazonaws.com/0/193272/370faf06-ed6f-bc24-cb87-e287619b0e8b.png">

ZABBIXでalertが発生したときのスクリプトに指定してZABBIXと連携なども出来そうです
## ServiceNow Script(JavaScript)で自分自身のInstanceに対して実行してみる
REST API ExplorerでPOSTでIncidentのShort Descriptionに値を追加する設定にします(cURLと手順は一緒です)
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/193272/170a09fd-5fa4-5e1a-cf49-f40504a18a53.png)
[Send]をクリックして201で成功したことを確認して
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/193272/bc7b6673-5498-22dc-af5f-56f857c8f3b2.png)
[ServiceNow Script]をクリックするとServiceNow Script Code Sampleのダイアログが表示されるので
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/193272/4967defc-56d9-94a7-ed1b-ec71dad1d763.png)
[Select Snippet]をクリックするソースが選択されるのでCtrl + Cでコピーして
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/193272/e8630f51-b4b4-aa2a-9518-50b0d2e7c3ab.png)
Filter navigatorにScripts - Backgroundと入力するなどしてScripts - Backgroundに移動してRun scriptのテキストボックスにCtrl + Vでペーストしてvar password = 'admin';の箇所を必要に応じて編集して
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/193272/40a1cfda-e9a4-176f-5e93-def81d4de288.png)
[Run script]で実行して
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/193272/23a3f2fa-4bf4-4e76-50b9-70e776596210.png)
POST先のIncidentを確認したらレコードが追加されていました
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/193272/aa3d7ccb-b1da-b0d4-1d02-8e8bff563526.png)
# コピペ用

```
var request = new sn_ws.RESTMessageV2();
request.setEndpoint('https://********.service-now.com/api/now/table/incident');
request.setHttpMethod('POST');

//Eg. UserName="admin", Password="admin" for this code sample.
var user = 'admin';
var password = 'admin';
 
request.setBasicAuth(user,password);
request.setRequestHeader("Accept","application/json");
request.setRequestHeader('Content-Type','application/json');
request.setRequestBody("{\"short_description\":\"from localhost\"}");
var response = request.execute();
gs.log(response.getBody());
```