Rest API’s in ServiceNow

Sushmitha Bhat
8 min readApr 17, 2024

--

REST APIs in ServiceNow help different software systems talk to each other, like a universal translator. They allow ServiceNow to share its data and functions with other applications easily, making it more flexible and integrated with the broader technology ecosystem.

Source : https://beingfluid.in/IntegrateNow/images/app_store_learnv2_rest_sandiego_inbound_images_inbound_genericrequest.png

Table of Contents:

  1. Introduction
  2. Setting Up ServiceNow Development Environment
  3. Creating a Custom Table for Book Data
  4. Writing a Script Include for Book Operations
  5. Developing a Scripted REST API for Book Management
  6. Testing Book API Endpoints in REST API Explorer
  7. Conclusion

1. Introduction:

In this article, we’ll explore how to create a custom Book API in ServiceNow. We’ll walk through the process of setting up the development environment, creating a custom table to store book data, writing a Script Include to encapsulate book operations, and developing a Scripted REST API to expose endpoints for interacting with the book data.

Overview of how scriptInclude is connected to Scripted Rest API to get the EndPoints

2. Setting Up ServiceNow Development Environment:

  • Sign in to your ServiceNow instance.
  • Navigate to the Studio application.
  • Create a new application for the Book API development. Here in this example I have named LibraryBook .

3. Creating a Custom Table for Book Data:

  • Go to System Definition > Tables.
  • Create a new table definition named Book and scope be likex_1331190_libraryb_book
  • Add fields such as Title, Author, and ISBN to store book information.

4. Writing a Script Include for Book Operations:

  • Go to System Definition > Script Includes.
  • Create a new Script Include named BookAPI.
  • Write JavaScript functions to encapsulate CRUD operations for managing book data.

ScriptInclude Script :

var BookAPI = Class.create(); // Define a new class for the BookAPI
BookAPI.prototype = { // Define the prototype methods for the BookAPI class
initialize: function() {}, // Constructor function, no initialization needed

// Function to retrieve all books from the custom table
getAllBooks: function() {
var bookList = []; // Initialize an empty array to store books
var bookGR = new GlideRecord("x_1331190_libraryb_book"); // Create a new GlideRecord object for the custom table
bookGR.query(); // Execute a query to retrieve all records from the table
while (bookGR.next()) { // Loop through each record in the GlideRecord
var book = { // Create an object to represent a book
id: bookGR.getUniqueValue(), // Get the unique identifier of the book record
title: bookGR.getValue("title"), // Get the title of the book
author: bookGR.getValue("author"), // Get the author of the book
isbn: bookGR.getValue("isbn") // Get the ISBN of the book
};
bookList.push(book); // Add the book object to the array
}
return bookList; // Return the array of books
},

// Function to retrieve a book by its ID
getBookByID: function(bookID) {
var bookGR = new GlideRecord("x_1331190_libraryb_book");
if (bookGR.get(bookID)) { // Check if a book with the given ID exists
var book = {
id: bookGR.getUniqueValue(),
title: bookGR.getValue("title"),
author: bookGR.getValue("author"),
isbn: bookGR.getValue("isbn")
};
return book; // Return the book object
} else {
return null; // Return null if the book is not found
}
},

// Function to create a new book record
createBook: function(title, author, isbn) {
var bookGR = new GlideRecord("x_1331190_libraryb_book"); // Create a new GlideRecord object
bookGR.initialize(); // Initialize the GlideRecord for insertion
bookGR.setValue("Title", title); // Set the title of the book
bookGR.setValue("Author", author); // Set the author of the book
bookGR.setValue("ISBN", isbn); // Set the ISBN of the book
var bookID = bookGR.insert(); // Insert the book record into the table and get the unique identifier
return bookID; // Return the unique identifier of the newly created book
},

// Function to update an existing book record
updateBook: function(bookID, title, author, isbn) {
var bookGR = new GlideRecord("x_1331190_libraryb_book"); // Create a new GlideRecord object
bookGR.query(); // Execute a query to retrieve records from the table
if (bookGR.get(bookID[0])) { // Check if a book with the given ID exists
bookGR.setValue("title", title); // Set the title of the book
bookGR.setValue("author", author); // Set the author of the book
bookGR.setValue("isbn", isbn); // Set the ISBN of the book
bookGR.update(); // Update the book record in the table
return true; // Return true to indicate successful update
} else {
return false; // Return false if the book is not found
}
},

// Function to delete an existing book record
deleteBook: function(bookID) {
var bookGR = new GlideRecord("x_1331190_libraryb_book"); // Create a new GlideRecord object
if (bookGR.get(bookID[0])) { // Check if a book with the given ID exists
bookGR.deleteRecord(); // Delete the book record from the table
return true; // Return true to indicate successful deletion
} else {
return false; // Return false if the book is not found
}
},

type: 'BookAPI' // Define the type of the BookAPI class
};

5. Developing a Scripted REST API for Book Management:

  • Go to System Web Services > Scripted REST APIs.
  • Create a new Scripted REST API named BookAPI.
  • Write JavaScript code to handle HTTP requests (GET, POST, PUT, DELETE) for book management using the functions defined in the BookAPI Script Include.
  • Name of the API is book_api
Handle HTTP requests in Scripted Rest Service

Create New API request as shown in second slide above. Inside that request write your scripts

Script for GET request
// GET Method

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
try{
var queryParams = request.queryParams; // Get the query parameters from the request
var bookAPI = new x_1331190_libraryb.BookAPI(); // Create an instance of the BookAPI class
var result = {}; // Initialize an empty object to store the result
if (queryParams && queryParams.id) { // Check if query parameters contain an ID
// If there is an ID in query parameters, retrieve a single book
result = bookAPI.getBookByID(queryParams.id);
} else {
// If no ID is provided, retrieve all books
result = bookAPI.getAllBooks();
}
response.setStatus(200); // Set the HTTP response status to 200 (OK)
response.setContentType('application/json'); // Set the content type of the response to JSON
response.getStreamWriter().writeString(JSON.stringify(result)); // Write the result object as a JSON string to the response
}catch(error){
response.setStatus(500); // Set the HTTP response status to 500 (Internal Server Error)
response.setBody({
message:"Please wait,something has caughtup...!", // Set a generic error message
err:error.toString() // Set the error details in the response body
});
}

})(request, response); // Execute the anonymous function with the provided request and response objects
//POST Method

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
try {
var queryParams = request.queryParams; // Get the query parameters from the request
var requestBody = JSON.stringify(request.body.dataString); // Get the request body data as a JSON string

var bookAPI = new x_1331190_libraryb.BookAPI(); // Create an instance of the BookAPI class
var result = {}; // Initialize an empty object to store the result

// Call the createBook function of the BookAPI class with data from the request body
result = bookAPI.createBook(
requestBody.title,
requestBody.author,
requestBody.isbn
);

response.setStatus(200); // Set the HTTP response status to 200 (OK)
response.setContentType("application/json"); // Set the content type of the response to JSON
response.getStreamWriter().writeString(JSON.stringify(result)); // Write the result object as a JSON string to the response
} catch (error) {
response.setStatus(500); // Set the HTTP response status to 500 (Internal Server Error)
response.setBody({
message: "Please wait, something has caught up...!", // Set a generic error message
err: error.toString(), // Set the error details in the response body
});
}
})(request, response); // Execute the anonymous function with the provided request and response objects
//PUT Method

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
try {
var queryParams = request.queryParams; // Get the query parameters from the request
// var requestBody = JSON.stringify(request.body.dataString); //Dont do stringify here
var requestBody = request.body.data; // Get the request body data

var bookAPI = new x_1331190_libraryb.BookAPI(); // Create an instance of the BookAPI class
var result = {}; // Initialize an empty object to store the result

// Call the updateBook function of the BookAPI class with data from the request body
result = bookAPI.updateBook(
queryParams.id,
requestBody.title,
requestBody.author,
requestBody.isbn
);

response.setStatus(200); // Set the HTTP response status to 200 (OK)
response.setContentType("application/json"); // Set the content type of the response to JSON
response.getStreamWriter().writeString(JSON.stringify(result)); // Write the result object as a JSON string to the response
} catch (error) {
response.setStatus(500); // Set the HTTP response status to 500 (Internal Server Error)
response.setBody({
message: "Please wait, something has caught up...!", // Set a generic error message
err: error.toString(), // Set the error details in the response body
});
}
})(request, response); // Execute the anonymous function with the provided request and response objects
//DELETE Method

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
try {
var queryParams = request.queryParams; // Get the query parameters from the request

var bookAPI = new BookAPI(); // Create an instance of the BookAPI class
var result = {}; // Initialize an empty object to store the result

// Call the deleteBook function of the BookAPI class with the book ID from query parameters
result = bookAPI.deleteBook(queryParams.id);

response.setStatus(200); // Set the HTTP response status to 200 (OK)
response.setContentType("application/json"); // Set the content type of the response to JSON
response.getStreamWriter().writeString(JSON.stringify(result)); // Write the result object as a JSON string to the response
} catch (error) {
response.setStatus(500); // Set the HTTP response status to 500 (Internal Server Error)
response.setBody({
message: "Please wait, something has caught up...!", // Set a generic error message
err: error.toString(), // Set the error details in the response body
});
}
})(request, response); // Execute the anonymous function with the provided request and response objects

6. Testing Book API Endpoints in REST API Explorer:

  • Go to System Web Services > REST API Explorer.
  • Find the BookAPI Scripted REST API and expand it.
  • Test each endpoint using the provided interface.
  • Use request body to pass data to the endpoints (e.g., create, update) and observe the responses.
Screenshot of the RestAPI Explorer page

Request Body for POST request looks like :

post request body

Response Body for POST request :

Response for post request

For PUT request enter the JSON in below format:

//PUT and POST request Request Body

{
"title": "New Book Title",
"author": "Author Name",
"isbn": "ISBN Number"
}
enter the JSON in Raw block

7. Conclusion:

I’ve demonstrated the step-by-step process of creating a custom Book API in ServiceNow, from setting up the development environment to testing endpoints in REST API Explorer. Feel free to let me know any changes required in this article.

--

--

Responses (1)