sabell2012
Mega Sage
Mega Sage

NOTE: MY POSTINGS REFLECT MY OWN VIEWS AND DO NOT NECESSARILY REPRESENT THE VIEWS OF MY EMPLOYER, ACCENTURE.

 

DIFFICULTY LEVEL: INTERMEDIATE
Assumes a good knowledge and/or familiarity of REST web services and Scripting in ServiceNow. Assumes having taken the class SSNF and has good intermediate level of knowledge and/or familiarity with Scripting in ServiceNow. 


Some time ago I had to create a REST Web Message to retrieve information from a server. It occurred to me that there really had not been many examples written on this for ServiceNow. At least from the code perspective. So I thought I would share. This really isn't that complicated, and you should be able to glean what you need from the ServiceNow documentation, but I thought I would present a working example to play with anyway.

 

In this example we will be using a test REST web service site called: 'cat-facts'. This will return a success string (true/false), and from 1 to any number we specify; of facts about cats.

 

The idea here is to retrieve data from a REST Web Service and then parse the results into a JSON object for further use.

 

What is needed:

 

  1. Web Service end-point. This will be: 
    1. https://catfact.ninja/facts?limit=<<some number>>
    2. If the number is not provided it is automatically assumed to be 10.
  2. ServiceNow REST Message
  3. Fix Script to run our test code and parse the results

 


Lab 1.1: Creating the Rest Message

 

  1. Navigate to System Web Services > REST Message.
  2. Click on the New button to create a new REST Message.
  3. Fill in the form with the following:
    1. Name: CatFacts
    2. Accessible from: All application scopes
    3. Description: Retrieve facts about cats!
    4. Endpoint: https://catfact.ninja/facts 
    5. Authentication type: No authentication
    6. Right-click on the form header and choose Save. This will auto-generate four HTTP methods (get, put, post, delete).   We will only be using "get" for the purposes of this article.

 

sabell2012_0-1703804168873.png

 

4. In the HTTP Methods related list click on the "Default GET" method.

5. Change the Endpoint to: https://catfact.ninja/facts?limit=${limit}

6. Right-click on the form header, and Save your work.

7. Scroll to the bottom of the form and from the Variable Substitution related list click the New button.

8. Fill out the form with the following:

a. Name: limit

b. Escape type: No escaping

c. Test Value: 5      <- we will be pulling back five facts about cats.

d. Click Submit to save the variable.

 

sabell2012_3-1703804651276.png

 

9. Scroll down to the bottom of the Method form, and choose the "Test" link under the related links.  

This will execute the REST Message with the number value of 5.  

10. You will get a 200 result (success), and five facts about cats!

 

sabell2012_4-1703804734431.png

 

Our REST Message is now ready to be consumed - a fancy programmer term meaning: "used".

 

 

Lab 1.2: Fix Script to Run Consume the REST Message

 

So now comes the cool stuff. We will be creating code to execute the REST Message, and then convert the response to a JSON object so that we can actually make some use of it.

 

  1. Navigate to Fix Scripts.
  2. Click the New button.
  3. Fill out the form with the following:
    1. Name: Cat Facts
    2. Description: Test script to consume the CatFacts REST Message
    3. Script:

 

var location = 'FS: CatFacts';
var webService = 'CatFacts';
var command = 'Default GET'; // case sensitive
var limit = 5;
var message = gs.getMessage('---> [{0}]\n', [location]);

try {
	var restMessage = new sn_ws.RESTMessageV2(webService, command);
	restMessage.setStringParameter('limit', parseInt(limit));
	var response = restMessage.execute(); // REST return
	var httpStatus = response.getStatusCode(); // response status code

	var responseBody = response.getBody(); // stringified JSON returned info
	var jsonBody = JSON.parse(responseBody); // turn it into a true JSON object

	// Now we can begin using the response
	message += gs.getMessage('\tResponseBody: {0}\n', [responseBody]);

	var facts = jsonBody.data;
	var success = httpStatus == 200;

	message += gs.getMessage('\tfacts.length: {0}\n', [facts]);
	message += gs.getMessage('\tjsonBody.success: {0}\n', [success]);
	message += 'Facts:\n';
	if (success) {
		for (var i = 0; i < facts.length; i++) {
			message += gs.getMessage('\t[{0}]: {1}\n', [i, facts[i].fact]);
		}
	}
}
catch(err) {
	gs.error('---> ERROR: ' + err);
}
gs.info(message);

 

4. Right-click on the form header and Save your work.

 

sabell2012_8-1703805674456.png

 

5. Navigate to System Logs > System Log > All and filter Message for --->

 

sabell2012_7-1703805632061.png


And there you have it! In this article I demonstrated:

 

  1. How to create a REST Message
  2. How to add a variable to the REST Message method
  3. How to test a REST Message method
  4. How to call a REST Message from a script
  5. How to use a variable in a REST Message from a script
  6. How to parse the returned results into JSON from the REST Message
  7. How to consume (a.k.a. use) the JSON results

 

Enjoy!

Steven Bell.

 

If you find this article helps you, don't forget to log in and mark it as "Helpful"!

 

sabell2012_0-1703794648636.png


Originally published on: 09-06-2016 01:50 AM

I updated the code, fixed broken links, and brought the article into alignment with my new formatting standard

13 Comments