ServiceNow Table API – Integrate using cURL, Python, Ruby, JavaScript, Perl or Powershell

Below, I’ll show you how you can use 7 different scripting languages to authenticate to ServiceNow and retrieve/consume data. You can integrate with ServiceNow with the following scripting languages (not limited to): ServiceNow Scripting, JavaScript, …

Newsletter Signup

Want to get better at ServiceNow?
(One email per month)

Rest API Explorer

Below, I’ll show you how you can use 7 different scripting languages to authenticate to ServiceNow and retrieve/consume data.

You can integrate with ServiceNow with the following scripting languages (not limited to):

ServiceNow Scripting, JavaScript, Python, Ruby, Perl, Powershell and cURL scripting.

All of the code examples below are going to retrieve 1 record from the incident table, and will print it out, if entered correctly into your IDE of choice.

If you’d like to consume ServiceNow data, from any external 3rd party, you can easily implement the below script(s) to do so.

You’ll just need to authenticate, and pass in the table you’re trying to reach.

In the out of box configuration of ServiceNow, to run a GET request – you only need the ITIL role. It’s quite possible that the ServiceNow team at your company has modified this, if the below code examples don’t work as expected.

The below examples use ServiceNow’s Table API Endpoint.

The endpoint for the ServiceNow Table API is:

https://instance_name.service-now.com/api/now/table/{tableName}

These code examples are all available at the bottom of the ServiceNow REST API Explorer.

Just a little piece of information to be aware of ahead of time. You will need to make a small change to the scripts, so it works.

If you’d like to try this out, and you don’t have a ServiceNow Environment (or don’t want to use your companies environment) – ServiceNow gives anyone a free instance to play around with. Go make an account and create a new instance here: ServiceNow Developer Portal

We’re going to recommend that you don’t try this in production, the firs time around. Even though it’s a GET request, the below scripts do not update any information – they just retrieve data. Still, it’s best to do this in sub-production (DEV/TEST) and it’s important to have some basic programming knowledge before you proceed.

Code Examples

For all of the examples you’ll need to do 2 things to successfully authenticate with your script of choice:

  1. Change instance_name to your ServiceNow Instance
  2. Change the username and password (admin: admin has been set by default, this will not work if you try it in your instance). And if it does, change that admin password!

ServiceNow Scripting

var request = new sn_ws.RESTMessageV2();
request.setEndpoint('https://instance_name.service-now.com/api/now/table/incident?sysparm_limit=1');
request.setHttpMethod('GET');

//Eg. UserName="admin", Password="admin" for this code sample.
var user = 'admin';
var password = 'admin';

request.setBasicAuth(user,password);
request.setRequestHeader("Accept","application/json");

var response = request.execute();
gs.log(response.getBody());

cURL

curl "https://instance_name.service-now.com/api/now/table/incident?sysparm_limit=1" \
--request GET \
--header "Accept:application/json" \
--user 'admin':'admin'

Python

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

# Set the request parameters
url = 'https://instance_name.service-now.com/api/now/table/incident?sysparm_limit=1'

# 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.get(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

#!/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_name.service-now.com/api/now/table/incident?sysparm_limit=1'
 
 # Eg. User name="admin", Password="admin" for this code sample.
user = 'admin'
pwd = 'admin'

request_body_map = "";
 
 begin
   response = RestClient.get("#{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

var requestBody = ""; 

var client=new XMLHttpRequest();
client.open("get","https://instance_name.service-now.com/api/now/table/incident?sysparm_limit=1");

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

#!/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_name.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->GET("/api/now/table/undefined?sysparm_limit=1",
                
                {'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

# 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_name.service-now.com/api/now/table/incident?sysparm_limit=1"

# Specify HTTP method
$method = "get"




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

# Print response
$response.RawContent


For a more detailed list of methods for the ServiceNow API, navigate: here.

We’d love to see if you have any questions below.

Leave a Comment