image of a laptop with coding

Scripting for the ServiceNow Cart

As a ServiceNow partner, we are often tasked with helping to automate processes within ServiceNow. Though a hallmark of the ServiceNow platform is providing access to a self-service Service Catalog, requests could reasonably be expected to need to be generated from any number of other processes where having to manually fill out a catalog item would be redundant or inconvenient. To help us with this is a “cart API,” provided by ServiceNow, which is available from any server-side context.

As an example, I’ll present a script that would hypothetically be used to order a laptop using the cart API. This could exist in a business rule or workflow or any other context where it would be useful.

var id = GlideGuid.generate(null); // Generate a new GUID
var cart = new Cart(id); // Instantiate a fresh cart
var RITM = cart.addItem('060f3afa3731300054b6a3549dbe5d3e');  // The value used here is the sys_id of our laptop catalog item
cart.setVariable(RITM,'ram','16');       /**/
cart.setVariable(RITM,'os','win10');     /* Catalog item variables can be populated */  
cart.setVariable(RITM,'storage','1tb');  /**/
var request = cart.placeOrder();  // The placeOrder() function returns a GlideRecord for the sc_request record it generates

Additionally, another API available within SN may be needed for interacting with the cart. Specifically, within a scoped context, you’ll want to make use of the CartJS API. Below is an example of how to use this API to complete the same objective as the script above.

var cart = new sn_sc.CartJS();
var item = { // Note that values using CartJS are instantiated via a JSON object
	'sysparm_id': '060f3afa3731300054b6a3549dbe5d3e',
	'sysparm_quantity': '1',
	'variables': {
		'ram': '16',
		'os': 'win10',
		'storage': '1tb'
var cartVals = cart.addToCart(item); // The addToCart function returns a JSON object reflecting the status of the cart
var checkoutVals = cart.checkoutCart(); // The checkoutCart function returns a JSON object with info about the submitted cart, contents varying if two-step checkout is active

Both options for request creation via script have additional configuration options that can be found within ServiceNow’s documentation.