scripted rest api servicenow

Scripted REST API

What is an API ?

API stands for Application Programming Interface. The word Application refers to any software with a distinct function. Interface can be thought of as a contract of service between two applications. This contract defines how the two communicate with each other using requests and responses.

What is Scripted REST API ?

The scripted REST API feature allows us to build custom web service APIs. It is a web service that one can build and configure to allow external systems to talk to ServiceNow. You can define service endpoints, query parameters, and headers for a scripted REST API, as well as scripts to manage the request and response.

When to use a scripted REST API?

    • We can use scripted REST API when there is a requirement of interaction between two applications and if there are multiple conditions involved.
    • If an external system needs to send data to Service Now and if you need to process custom changes(validations etc) which are not supported by OOB REST API’s then you can write a scripted REST web service to process inbound requests from external systems.

Scripted REST API vs REST API explorer:

In servicenow, we may use REST API explorer as well for CRUD operations. But, this comes with a limitation.

      1. Rest Message is used for sending outbound updates to an external system from Service Now. If a third party application supports REST then you can send data from Service Now using the rest message.

However, a Scripted REST API enables inbound updates from an external system.

2. The REST API explorer cannot be customized. For example: if there is a requirement to update a record in one of the application based on certain condition. It won’t be possible for us to customize the API to perform the action.

However, a scripted REST API is designed to carry out these requirements via scripting.

Scripted REST API roles:

To work with scripted REST APIs, you must have the web service administrator [web_service_admin] role. Users with this role can read, create, modify, and delete scripted REST APIs and web service resources.

Note: These roles are not required to access a scripted REST API endpoint.

Request and response formats:

By default, all resources in an API support the following request and response formats: application/json, application/xml, and text/xml. You can overrride the default formats at the API level. The new formats apply to all resources belonging to the API, unless an individual resource overrides the defaults.

How to create a Scripted REST API URIs:

Scripted REST API URIs have the following format:

https://<instance.service-now.com>/api/<name_space>/<version>/<api_id>/<relative_path>

Lets understand each component of URI:

      1. <instance.service-now.com>: Path to the ServiceNow instance where users access the scripted REST API.
      2. <name_space>: For web services in the global scope, the name space is the value of the property glide.appcreator.company.code. For web services in a scoped application, the name space is the scope name, such as x_company_appname. For additional information on name spaces.
      3. <version>: Optional. Version of the endpoint to access if the API uses versioning, such as v1. You can access the default version of a versioned API by specifying the URI without a version number.
      4. <api_id>: Value of the API ID field on the Scripted REST Service form. By default this value is based on the service name.
      5. <relative_path>: Relative path defined for the resource in the Scripted REST Service form. Specifying a relative resource path allows you to have multiple resources using the same HTTP method, such as GET, in one web service. For example, a resource may specify the path /{id} when the web service has only one GET resource, or /user/{id} and /message/{id} when the web service has different resources for requesting user and message records.

Example URI:
Example URI:

https://dev7109.servicenow.com/api/34257/applicationintegration/insert_update_incident

 

Use Case/Practical scenarios:

Scenario-1: A client shares a requirement to capture alerts generated from a monitoring tool (Solarwinds, Prometheus, Datadog etc ) and create an incident for it on ServiceNow

Scenario-2: To make it a little complex, it is required to create an incident when the status is “DOWN” for any CI and resolve the incident when the status is “UP” for the same CI

Scenario-3: It is again required to assign that particular incident to a specific user and make sure that for the same CI, multiple incidents do not get generated even after multiple alerts from the monitoring tool

Propose Solution:

Only Scenario-1 can be achieved by REST API explorer and here comes Scripted REST API in picture which can handle complexities defined in Scenario-2 & 3.

Create scripted REST API step by step:

    1. Navigate to System Web Services > Scripted Web Services > Scripted REST APIs.
    2. Create new record and type appropriate name “applicationintegration” and Save it.
    3. Scroll down and go to related list called “Resources” Create a new resource.
    4. Type name “insert_update_incident”. Select HTTP method “POST”. Type relative path “insert_update_incident”. Save it.
    5. Write a script in the “Script” box. Save it. You have to write two script. #1 will be in script attribute of Scripted REST Resource and #2 will be in script include.
(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
    var responseBody = {};
    var event = request.body.data;
    if (event.ci_status == "up") {
        var resolve_incident = new getApplicationAlert().update_incident();
        return resolve_incident;
    } else {
        var ci = new GlideRecord('incident');
        ci.addEncodedQuery('stateIN1,4,2,3');
        ci.addQuery('cmdb_ci.name', event.cmdb_ci);
            ci.query();
            if (ci.next()) {
                responseBody.message = "Inc exists for CI ";
                response.setBody(responseBody);
                ci.setAbortAction('true');
            } else {
                var insert_incident_1 = new getApplicationAlert().insert_incident();
                return insert_incident_1;
            }
    }
})(request, response); 

var getApplicationAlert  = Class.create();
getApplicationAlert .prototype = {
    initialize: function() {},
    get_ci_info: function() {
        var responseBody = {};
        var event = request.body.data;
        var ci = new GlideRecord('cmdb_ci');
        ci.addQuery('name', event.cmdb_ci);	
        ci.query();
            if (ci.next()) {
                return ci.name;
            }     
        },
    insert_incident: function() {
        var responseBody = {};
        var event = request.body.data;
        var caller = gs.getProperty('glide.incident.caller');
        var ci = this.get_ci_info();
        var gr = new GlideRecord('incident'); {
           gr.initialize();
           gr.caller_id = caller;
           gr.work_notes = event.work_notes;
           gr.short_description = event.short_description;
           gr.u_incident_type = '5';
           gr.category = "general";
           gr.subcategory = "incident";
           gr.description = event.description;
           gr.setDisplayValue('cmdb_ci', ci);
            if (ci != event.cmdb_ci) {
                responseBody.message = event.cmdb_ci+" - Configuration item does not exist";
                response.setBody(responseBody);
                gr.setAbortAction('true');
            } else {
                gr.insert();
                responseBody.message = "Incident created";
                responseBody.incidentnumber = gr.number;
                responseBody.incidentcaller = gr.caller_id;
                responseBody.incidentshortdescription = gr.short_description;
                responseBody.incidenttype = gr.u_incident_type;
                responseBody.ci = gr.cmdb_ci;
                response.setBody(responseBody);
            }
        }
    },
    update_incident: function() {
        var responseBody = {};
        var event = request.body.data;
        var ci = this.get_ci_info();
        var inc = new GlideRecord('incident');
        inc.addEncodedQuery('stateIN1,4,2,3');
        inc.addQuery('cmdb_ci.name', ci);
        inc.query();
        if (inc.next()) {
            inc.state = 6;
            inc.close_code = event.close_code;
            inc.close_notes = event.close_notes;
            inc.update();
        }
        responseBody.message = "Incident Updated.";
        responseBody.incidentnumber = inc.number;
        responseBody.incidentcaller = inc.caller_id;
        responseBody.incidentshortdescription = inc.short_description;
        responseBody.incidenttype = inc.u_incident_type;
        responseBody.ci = inc.cmdb_ci;
        response.setBody(responseBody);
    },
    type: 'getApplicationAlert '
};

 

  • Use the instance name and resource path to create a URI as below:

 

https://dev7109.servicenow.com/api/34257/applicationintegration/insert_update_incident

    1. Share this URI with the monitoring tool team and ask them to hit the API
    2. End

Testing Scripted REST API (via POSTMAN):

We can test our Scripted REST API using POSTMAN tool available online for free. Below are the steps to test:

    1. Create a user “RestUser” in ServiceNow with roles defined above.
    2. Open https://web.postman.co/
    3. Click on “Workspace”-> “My Workspace”.                 
    4. Click on Create new collection and name your collection “Scripted Rest API”.
    5. Click on Auth
    6. Select type: Basic Auth and provide the user credentials.
    7. Click on Body and provide input in the format below:
      {“cmdb_ci”:”app-azu-snow-te”,”ci_status”:”up”}
    8. A success will give you incident number in the response section and a failure would provide an error message.

Result:

 

Join Us

Thanks for reading this article, i hope you liked it, if that so, do like and subscribe my YouTube channel. You can also join our telegram channel to clear your technical doubt.

Q & A

Scripted rest api get method in servicenow

One common test we run, is using GET to retrieve data from ServiceNow. You will run GET methods to retrieve data programmatically from ServiceNow into another tool, where it can be used for processing or reporting. The URL for the GET method can most easily be retrieved from the REST api explorer in the instance: https://<instance.service-now.com/api/now/table/incident?sysparm_query=active%3Dtrue&sysparm_display_value=true&sysparm_limit=1 Each request will have a Header, where, for example authorization and content formatting information can be found, and a body, where the individual attributes will be filled.
Once the URL is entered, the authorization headers must be filled: Typically, we use Basic Auth, which is using userID and password, but the OAuth authentication method is also supported by ServiceNow.

How to create scripted REST API in ServiceNow?

1. Navigate to System Web Services > Scripted Web Services > Scripted REST APIs
2. Create new record and type appropriate name “applicationintegration” and Save it.
3. Scroll down and go to related list called "Resources" Create a new resource.

4. Type name “insert_update_incident”. Select HTTP method “POST”. Type relative path “insert_update_incident”. Save it.
5. Write a script in the “Script” box. Save it. You have to write two script. #1 will be in script attribute of Scripted REST Resource and #2 will be in script include.

What is the difference between scripted REST API and table API in ServiceNow?

Scripted API allows data to be synthesized and formatted on the fly. Table API requires that the desired data already exists in the required format before being queried.

What are the 4 most common REST API operations?

REST APIs use a uniform interface, which helps to decouple the client and service implementations. For REST APIs built on HTTP, the uniform interface includes using standard HTTP verbs to perform operations on resources.
The most common operations are GET, POST, PUT, PATCH, and DELETE. REST APIs use a stateless request model.

 

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here