Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

tiagomacul
Giga Sage

ServiceNow incident Web API

webservice criando um incident

 

The very first thing

You need a user to post something in ServiceNow

Create a user

 

Acesso a documentação / documentation

https://<instance>.service-now.com/incident.do?WSDL

TO Create a record - Post Address / Endereço do Post

POST 
https://<instance>.service-now.com/api/now/table/{tableName}

Therefore for incident table

https://<instance>.service-now.com/api/now/table/incident

.

 CURL Sample

curl "https://<instance>.service-now.com/api/now/table/incident" \
--request POST \
--header "Accept:application/json" \
--user 'admin':'admin'



 

Python Sample

#Need to install requests package for python
#easy_install requests
import requests

# Set the request parameters
url = 'https://<instance>.service-now.com/api/now/table/incident'

# Eg. User name="admin", Password="admin" for this code sample.
user = 'admin'
pwd = 'admin'

# Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}

# Do the HTTP request
response = requests.post(url, auth=(user, pwd), headers=headers )

# Check for HTTP codes other than 200
if response.status_code != 200: 
    print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json())
    exit()

# Decode the JSON response into a dictionary and use the data
data = response.json()
print(data)

 

Ruby Sample

 #!/usr/bin/env ruby
 
 require 'base64'
 
 # https://rubygems.org/gems/json
 # Example install using gem
 #   gem install json
 require 'json'
 
 # https://rubygems.org/gems/rest-client
 # Example install using gem
 #   gem install rest-client
 require 'rest_client'
 
 # Set the request parameters
 url = 'https://<instance>.service-now.com/api/now/table/incident'
 
 # Eg. User name="admin", Password="admin" for this code sample.
user = 'admin'
pwd = 'admin'

request_body_map = "";
 
 begin
   response = RestClient.post("#{url}", 
                              {:authorization => "Basic #{Base64.strict_encode64("#{user}:#{pwd}")}",
                              
                              :accept => 'application/json'
                              })
   puts "#{response.to_str}"
   puts "Response status: #{response.code}"
   response.headers.each { |k,v|
     puts "Header: #{k}=#{v}"
   }
 
 rescue => e
   puts "ERROR: #{e}"
 end

 

JavaScript Sample

var requestBody = ""; 

var client=new XMLHttpRequest();
client.open("post","https://<instance>.service-now.com/api/now/table/incident");

client.setRequestHeader('Accept','application/json');
client.setRequestHeader('Content-Type','application/json');

//Eg. UserName="admin", Password="admin" for this code sample.
client.setRequestHeader('Authorization', 'Basic '+btoa('admin'+':'+'admin'));

client.onreadystatechange = function() { 
	if(this.readyState == this.DONE) {
		document.getElementById("response").innerHTML=this.status + this.response; 
	}
}; 
client.send(requestBody);

Perl Sample

 #!/usr/bin/env perl -w
 use strict;
 use warnings;
 use MIME::Base64;
 
 # http://search.cpan.org/~makamaka/JSON/lib/JSON.pm
 # Example install using cpanm:
 #   sudo cpanm -i JSON
 use JSON;
 
 # http://search.cpan.org/~mcrawfor/REST-Client/lib/REST/Client.pm
 # Example install using cpanm:
 #   sudo cpanm -i REST::Client
 use REST::Client;
 
 # Set the request parameters
 my $host = 'https://<instance>.service-now.com';
 
 # Eg. User name="admin", Password="admin" for this code sample.
 my $user = 'admin';
 my $pwd = 'admin';

 
 my $client = REST::Client->new(host => $host);
 
 my $encoded_auth = encode_base64("$user:$pwd", '');
 
 $client->POST("/api/now/table/incident",
                
                {'Authorization' => "Basic $encoded_auth",
                 
                 'Accept' => 'application/json'}); 
 
 print 'Response: ' . $client->responseContent() . "\n";
 print 'Response status: ' . $client->responseCode() . "\n";
 foreach ( $client->responseHeaders() ) {
   print 'Header: ' . $_ . '=' . $client->responseHeader($_) . "\n";
 }
 

Powershell Sample

# Eg. User name="admin", Password="admin" for this code sample.
$user = "admin"
$pass = "admin"

# Build auth header
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass)))

# Set proper headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))
$headers.Add('Accept','application/json')


# Specify endpoint uri
$uri = "https://<instance>.service-now.com/api/now/table/incident"

# Specify HTTP method
$method = "post"




# Send HTTP request
$response = Invoke-RestMethod -Headers $headers -Method $method -Uri $uri 

# Print response
$response.RawContent

another PowerShell sample

 

This video covers:

 

Specific sample posting is just summary

Request body

{"short_description":"test"}

Response

 

201 Created

Execution time (ms)
 
1542
Headers
Cache-Control
 
no-cache,no-store,must-revalidate,max-age=-1
Connection
 
keep-alive
Content-Encoding
 
gzip
Content-Type
 
application/json;charset=UTF-8
Date
 
Thu, 22 Sep 2022 14:25:47 GMT
Expires
 
0
Keep-Alive
 
timeout=20
Location
 
https://<instance>.service-now.com/api/now/table/incident/bbdd2e521bca9510df16da86cc4bcb2c
Pragma
 
no-store,no-cache
Server
 
ServiceNow
Server-Timing
 
sem_wait;dur=0, sesh_wait;dur=0
Strict-Transport-Security
 
max-age=63072000; includeSubDomains
Transfer-Encoding
 
chunked
X-Is-Logged-In
 
true
X-Transaction-Id
 
bbdda25e1b8a

 

Response body

{
  "result": {
    "parent": "",
    "caused_by": "",
    "watch_list": "",
    "upon_reject": "cancel",
    "sys_updated_on": "2022-09-22 14:25:47",
    "origin_table": "",
    "approval_history": "",
    "skills": "",
    "number": "INC0010010",
    "state": "1",
    "sys_created_by": "user.name",
    "knowledge": "false",
    "order": "",
    "cmdb_ci": "",
    "delivery_plan": "",
    "cmdb_ci_business_app": "",
    "contract": "",
    "impact": "3",
    "active": "true",
    "work_notes_list": "",
    "priority": "5",
    "sys_domain_path": "/",
    "business_duration": "",
    "group_list": "",
    "approval_set": "",
    "needs_attention": "false",
    "universal_request": "",
    "short_description": "test",
    "correlation_display": "",
    "delivery_task": "",
    "work_start": "",
    "additional_assignee_list": "",
    "notify": "1",
    "service_offering": "",
    "sys_class_name": "incident",
    "closed_by": "",
    "follow_up": "",
    "parent_incident": "",
    "reopened_by": "",
    "sn_ind_tsm_core_stage": "",
    "reassignment_count": "0",
    "assigned_to": "",
    "sla_due": "",
    "comments_and_work_notes": "",
    "escalation": "0",
    "upon_approval": "proceed",
    "correlation_id": "",
    "made_sla": "true",
    "sn_esign_document": "",
    "child_incidents": "0",
    "hold_reason": "",
    "task_effective_number": "INC0010010",
    "sn_ind_tsm_core_incident": "false",
    "resolved_by": "",
    "sys_updated_by": "tiago.macul",
    "opened_by": {
      "link": "https://everisbrasilconsultoriadenegociosedemo3.service-now.com/api/now/table/sys_user/a3ca552bdb879810abc062ed1396191f",
      "value": "a3ca552bdb879810abc062ed1396191f"
    },
    "user_input": "",
    "sys_created_on": "2022-09-22 14:25:47",
    "sys_domain": {
      "link": "https://everisbrasilconsultoriadenegociosedemo3.service-now.com/api/now/table/sys_user_group/global",
      "value": "global"
    },
    "route_reason": "",
    "calendar_stc": "",
    "closed_at": "",
    "business_service": "",
    "business_impact": "",
    "rfc": "",
    "time_worked": "",
    "expected_start": "",
    "opened_at": "2022-09-22 14:25:47",
    "work_end": "",
    "caller_id": "",
    "reopened_time": "",
    "resolved_at": "",
    "subcategory": "",
    "work_notes": "",
    "close_code": "",
    "assignment_group": "",
    "business_stc": "",
    "cause": "",
    "description": "test",
    "origin_id": "",
    "calendar_duration": "",
    "close_notes": "",
    "sys_id": "bbdd2e521bca9510df16da86cc4bcb2c",
    "contact_type": "",
    "sn_esign_esignature_configuration": "",
    "incident_state": "1",
    "urgency": "3",
    "problem_id": "",
    "company": "",
    "activity_due": "",
    "action_status": "",
    "severity": "3",
    "comments": "",
    "approval": "not requested",
    "due_date": "",
    "sys_mod_count": "0",
    "reopen_count": "0",
    "sys_tags": "",
    "location": "",
    "category": "inquiry"
  }
}

 

The sample post depends on the ServiceNow Implementation therefore be careful and ask for an administrator, another sample was in a specific implementation about mandatory fields

 

 

 

Summary

Script Summary

REST API reference

Integrate with ServiceNow

Veja aqui como testar o webservice!

Scripted rest API - Building your API on the ServiceNow

Can a "Web service access only" user allow this user to connect to the instance

Creating ServiceNow Incidents via REST API

Updating variables

Most used tables / Principais tabelas.

Correlation

Tools

Version history
Last update:
‎09-22-2022 07:06 AM
Updated by: