LogiUpSkill

SOAP Integration

SOAP Integration 1.SOAP Integration:  SOAP (Simple Object Access Protocol) in ServiceNow is a protocol for exchanging structured data, primarily XML, used for integration with other systems, allowing ServiceNow to act as a web service provider or consumer by creating inbound (scripted) or outbound (SOAP Message) services, defining WSDLs, and managing security through roles like soap script, contrasting with REST’s architectural style but both serving data exchange needs within the platform.    2.Types of SOAP Integrations:  ServiceNow facilitates both inbound and outbound SOAP communications through different methods:   2.1 Inbound (Exposing ServiceNow data/logic to external systems)   Direct Web Services: These are automatically generated for every table in the system, providing standard methods like get, getKeys, insert, update, and delete if the user account has the appropriate roles (e.g., soap role).  Scripted SOAP Services: For more complex, custom logic and operations not covered by direct web services, developers can create scripted SOAP services. These allow for full control over the incoming request (input parameters) and outgoing response (output parameters) using server-side JavaScript.   2.2 Outbound (Consuming external web services from ServiceNow)  SOAP Message Functionality: ServiceNow provides a capability to define and send SOAP messages to external endpoints.  3.WSDL :  All tables and import sets dynamically generate Web Service Definition Language (WSDL) XML documents that describe its table schema and available operations.   You can obtain a table’s WSDL by issuing a URL call to your instance that contains the name of the table and the WSDL parameter.   For example:   https://myinstance.service-now.com/incident.do?WSDL     REST vs SOAP: No                              SOAP                                      REST  1.  SOAP is a protocol.      REST is an architectural style.  2.  SOAP stands for Simple Object Access Protocol.     REST stands for Representational State Transfer.  3.  SOAP can’t use REST because it is a protocol and can use any protocol like HTTP, SOAP.  REST can use SOAP web services because it is a concept  4.  SOAP uses services interfaces to expose the business logic.    REST uses URI to expose business logic.  5.  SOAP defines standards to be strictly followed.  REST does not define too much standards like SOAP.  6.  SOAP requires more bandwidth and resource than REST.     REST requires less bandwidth and resource than SOAP.  7.  SOAP defines its own security.      RESTful web services inherits security measures from the underlying transport.   8.  SOAP permits XML data format only.     REST permits different data format such as Plain text, HTML, XML, JSON etc.  9.  SOAP is less preferred than REST.             REST more preferred than SOAP.    Use Case: Integrate two ServiceNow instance. Every time when incident is created in one ServiceNow instance (source) then incident record with same information will also get created in another ServiceNow instance (target).    5.1. Complete the Target Instance Setup (Inbound)  created an Inbound SOAP Web Service that allows external systems to send SOAP   requests to ServiceNow.    Target Table:  Incident [incident].  Fields: Click “Create” on that form. ServiceNow will automatically create a staging table (likely called u_incident_creation) and a Transform Map.  The WSDL: Once you hit Create, the system generates a WSDL for this specific staging table. The URL will look like this: https://<TARGET_INSTANCE>.service-now.com/u_incident_creation.do?WSDL  5.1.1  : Import Table (u_incident_creation)  This table temporarily stores incoming SOAP data.  Fields like:  u_caller_id  u_short_description  u_number  u_active  etc.  Why this is needed?  SOAP does not insert directly into incident. Instead:  SOAP → Import table → Transform map → Incident  This gives: Validation                          Mapping control                          Business rule execution    5.1.2 : Transform Map (Core Logic)  Maps data from:  u_incident_creation  →  incident    Important settings  Active  Run business rules   Enforce mandatory fields (No)  Coalesce on u_number → number  Prevents duplicate incidents if number already exists  5.1.3: WSDL (Service Definition)  WSDL URL  https://<TARGET_INSTANCE>.service-now.com/u_incident_creation.do?WSDL    What WSDL contains?  SOAP operations (insert, update, get, etc.)  Field definitions  XML structure expected by ServiceNow  External systems read this WSDL to know:  What fields to send  How to format XML  5.2. Create the Outbound SOAP Message (In the Source Instance)  Navigate to System Web Services > Outbound > SOAP Message.  Click New and provide a Name (e.g., Target_Incident_Integration).  Paste the WSDL URL from Step 1 into the WSDL field.  Authentication: Under the “Authentication” tab, select Basic and provide the credentials of a user in the Target instance (this user must have the itil and soap roles).  Click Save.  Once saved, click the Generate sample SOAP messages related link. This will create several functions (insert, update, delete, etc.) under the SOAP Message record.  5.2.1. Configure the “insert” Function  Open the insert function created in the previous step.  In the SOAP Message field, you will see an XML payload. Look for fields like <short_description>?</short_description>.  Replace the question marks with variables like ${short_description}. This allows you to pass data dynamically from the Source incident.  Click on “Auto Generate Variables” to create variables in variable specification.  Tip: You only need to include the tags for the fields you want to sync (e.g., short_description, description, caller_id).  5.3. Create the Business Rule (In the Source Instance)  Navigate to System Definition > Business Rules and click New.  Table: Incident  When: after  Insert: Checked  5.3.1. Initializing the SOAP Message    var s = new sn_ws.SOAPMessageV2(‘Demo Outbound Integration’, ‘insert’);   This line creates an instance of the SOAPMessageV2 API.  It looks for the Outbound SOAP Message record named ‘Demo Outbound Integration’.  It specifically targets the insert function you generated earlier.  5.3.2. Passing Dynamic Data (Mapping)    s.setStringParameterNoEscape(‘insert.u_active’, current.active); s.setStringParameterNoEscape(‘insert.u_caller_id’, current.caller_id); s.setStringParameterNoEscape(‘insert.u_number’, current.number); s.setStringParameterNoEscape(‘insert.u_short_description’, current.short_description);   setStringParameterNoEscape: This function takes the data from your current record and plugs it into the XML variables you defined in your SOAP Envelope.  current.field_name: This refers to the data in the Incident you just saved in the Source instance.  insert.u_field_name: These are the variable names (the “Name” column in your last screenshot) that correspond to the fields on your Target’s staging table.  5.3.3 Execution and Response    var response = s.execute(); var responseBody = response.getBody(); var status = response.getStatusCode(); gs.addInfoMessage(‘Record Inserted’);   s.execute(): This is the “send” button. It physically sends the XML packet over the internet to the Target instance.  getStatusCode(): This captures the HTTP result. A 200 or 201 usually means success, while 401 or 500 indicates an error.  gs.addInfoMessage: This displays a blue banner at the top of your screen in ServiceNow to let the user know the integration script ran.      5.4. Incident Creation (Source Instance)   What happens here:  User creates Incident:  Caller: Beth Angelin  Short description: SOAP Outbound Integration  Business Rule triggers  SOAP Message executes automatically  5.5. Incident Created in Target Instance  Final Result:  Target instance receives SOAP call  Incident is created   Data matches source incident  Integration works successfully 

Rest Integration

Rest Integration Integration Integration means connecting ServiceNow with another application (like Workday, Jira, SAP, or any external system) so they can send and receive data automatically.  Example:  Workday sends employee data → ServiceNow creates/updates users  ServiceNow sends incident data → Another system processes it  2 . REST Integration:  REST (Representational State Transfer) is a way for systems to communicate over the internet using HTTP methods like GET (read), POST (create), PUT (update), and DELETE (delete).  2.1 Type Of Rest Integration:  Inbound REST Integration: External tools (like another app or ServiceNow instance) send data to your ServiceNow instance (e.g., create an incident).  Outbound REST Integration : Your ServiceNow instance sends data to external tools (e.g., notify another system about a new incident).  3.Whatis REST API?  Representational state transfer or REST is the most popular approach of building APIs. When a request for data is sent to a REST API, it’s usually done through hypertext transfer protocol (HTTP). Once a request is received, APIs designed for REST can return messages in a variety of formats: HTML, XML, plain text, and JSON.    A request is made up of four things:  The Endpoint  The method  The headers  The body        3.1 The Endpoint  The endpoint is the url you request for. It generally consists of a base path and resource path. E.g.  https://dev124645.service-now.com/api/now/table/incident   Every web service provider will have the API documentation, and that needs to be referenced in order to configure the HTTP method endpoint.    3.2 The Methods  HTTP methods define the action to take for a resource, such as retrieving information or updating a    record. The available HTTP Methods are:    3.2.1. POST: Create      The POST method is used to submit the information to the server.    3.2.2. GET: Read   The GET method is the most common of all the request methods. It is used to fetch the desired resource     from the server.    3.2.3. PUT: Update   Both PUT and PATCH are used to modify the resources on the server with a slight difference. PUT is a method of modifying resources where the client sends data that updates the entire resource.     3.2.3. PATCH: Update  PATCH is a method of modifying resources where the client sends partial data that is to be updated without modifying the entire data.    3.2.4. DELETE: Delete      The DELETE method is used to delete the resource identified by the request url.  3.2.5. Difference Between PUT and PATCH  Feature   PUT  PATCH  Primary Goal  Replace the entire resource.  Update specific fields (partial update).  Payload  Requires the complete record.  Requires only the changed fields.  Missing Fields  Traditionally sets missing fields to NULL or default.  Leaves missing fields untouched.  Record Creation  Can create a record if the sys_id doesn’t exist.  Fails (404 Error) if the record doesn’t exist.  Idempotency  Idempotent: Multiple identical requests have the same effect.  Not always idempotent: Repeated calls could lead to different results.      3.3 HTTP Headers:  Client and Server can pass the extra bit of information with the request and response using HTTP    headers. The Server determines which headers are supported or required.      The most widely used HTTP Headers are:  Accept  Content-Type    1.Accept      Type of data client can understand.    2.Content-Type      Specifies the media type of the resource.      3.4  Authorization:  To communicate with other applications or the target application, we need entry pass, means we need some key or credentials.  In ServiceNow we need Credentials (Username and Password). So, for that source instance need credentials of Target instance user. In ServiceNow we create user with rest_service role and share those details with source instance.    3.4.1 Types of Authentication:    3.4.1.1 Basic Authentication:  Basic Authentication is a straightforward, built-in HTTP protocol feature that works as follows:   Mechanism: The client sends credentials (username and password) in the HTTP header, which are encoded using Base64. This is an encoding, not encryption, so it must always be used over HTTPS to protect the credentials in transit.  Security: It offers minimal security and is highly vulnerable to interception if not secured by HTTPS. Credentials, once compromised, grant full, long-term access until manually changed.  Use Cases: It is best suited for small, internal applications, simple use cases, or rapid development where the overhead of a more complex system is not practical.   3.4.1.2 OAuth 2.0:  OAuth 2.0 is an industry-standard authorization framework (not an authentication protocol by itself, but used within them via OpenID Connect) designed for secure access delegation.     Mechanism: Instead of user credentials, it uses an “access token” (a temporary credential) which is obtained from an authorization server after the user/application grants permission. This token is then sent with subsequent API requests. The actual user credentials are only handled by the trusted authorization server.  Security: It provides enhanced security through:  Tokens: Tokens are short-lived and can be revoked.  Limited Scope: Access is limited to specific resources and actions defined by “scopes”.  No Password Sharing: The third-party application never sees the user’s actual password.  Grant Types: Different “flows” (e.g., Authorization Code, Client Credentials) are available for various application types (web, mobile, server-to-server) to maximize security in each scenario.  Use Cases: It is the standard for modern web and mobile applications, especially when integrating with third-party services (e.g., “Sign in with Google” or allowing a printing service to access your photos) and in large-scale enterprise systems.    4.Use Case    Integrate two ServiceNow instance. Every time when incident is created in one ServiceNow instance (source) then incident record with same information will also get created in another ServiceNow instance (target).    So the solution we will implement to achieve is that we will create rest message and Business rule in ServiceNow source instance and below are the required information which we need from Target instance or ServiceNow target instance, which will be needed while creating the rest message.  ENDPOINTS  METHODS  REQUEST BODY  HEADERS (CONTENT TYPE)  AUTHORIZATION DETAILS      4.1 Overall Flow (High Level)  Incident is created in Source instance  Business Rule triggers after insert/update  Business Rule calls a REST Message  REST Message sends data to Target instance  Target instance creates a new Incident using Table API  4.2 Source Instance  Step 1: Create REST Message (Source Instance)  Navigated to: System Web Services → Outbound → REST Message  REST Message acts as a container for:  Authentication  Base endpoint  Child HTTP methods  Authentication Configuration:  Authentication type: Basic  Basic Auth Profile: dev224187  Credentials belong to a user in the target instance   This allows the source instance to securely communicate with the target instance.  Step 2: Create HTTP Method (POST)  Created an HTTP Method under REST Message   HTTP Method: POST  Endpoint:  https://dev224187.service-now.com/api/now/table/incident   Why POST?  POST is used to create records  Here, it creates a new Incident in the target instance  Authentication:  Set to Inherit from parent  Uses the Basic Auth defined in REST Message      Step

ServiceNow JSON Parsing: Processing REST API Responses 

ServiceNow JSON Parsing: Processing REST API Responses  Use Case: When an Incident is created in Instance A, the caller information is sent to Instance B. Instance B fetches all incidents related to that caller and sends the incident details back to Instance A. Instance A parses the response and stores the incident data in a custom table.    Step 1: Create REST Message  Create a REST Message named AddCallerDetailsToCustomTable  Purpose: To communicate from Instance A to Instance B  Endpoint is the target ServiceNow instance (Instance B) where the request will be sent  Selected Authentication type: Basic  Chose an existing Basic Auth Profile (dev224187)  This profile contains:  Username  Password  Used to authenticate REST calls to Instance B  Step 2: Create HTTP Method  Selected HTTP Method = POST  Reason: Sending data (caller) to the target instance  Provided the Scripted REST API endpoint of Instance B  This endpoint points to the Scripted REST API created in Instance B  Added required headers to handle JSON data:  Accept: application/json  Content-Type: application/json  Ensures request and response are in JSON format  Step 3: Create Scripted REST Service (Instance B) Created a Scripted REST Service named AddCallerToCustomTable  Purpose: To receive caller-related incident data from another ServiceNow instance  Step 4: Create Scripted REST Resource  Created a Scripted REST Resource under the API AddCallerToCustomTable  Resource name: AddCallerToCustomTable  Selected HTTP Method: POST  This allows the source instance to send POST requests to this endpoint  1. Accept Incoming Request Payload  The resource is designed to accept JSON request body  Request body contains caller information sent from Instance A    (function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {      var requestBody = request.body.data;      var user = requestBody.caller;      var incidents = [];    2. Query Incident Table  Initialized a GlideRecord on the incident table  Filtered incidents based on the received caller_id:      var gr = new GlideRecord(‘incident’);      gr.addQuery(‘caller_id’, user);      gr.query();    3. Build Response Payload  Loop through all matching incident records  Collected required incident details:  Incident number  Short description  Stored them in an array:        while (gr.next()) {          incidents.push({              number: gr.getValue(‘number’),              short_description: gr.getValue(‘short_description’)          });      }    4. Send JSON Response  Returned the incident data as a JSON response  This response is sent back to Instance A        response.setBody({‘incidents’:incidents});  })(request, response);  Step 5: Create Business Rule (Instance A)  Navigate to System Definition > Business Rules and click New.  Table: Incident  When: after  Insert: Checked  Get Caller ID  Fetches the caller_id sys_id from the incident  This value is sent to another instance/API  (function executeRule(current, previous /*null when async*/ ) {      var user = current.caller_id.getValue();    Create Payload JSON payload containing the caller  Will be sent in REST request body      var payload = {          caller: user      };    Prepare REST Message Calls a Named REST Message  AddCallerDetailsToCustomTable → REST Message  AddCallerToCustomTable → HTTP Method        var restMessage = new sn_ws.RESTMessageV2(‘AddCallerDetailsToCustomTable’, ‘AddCallerToCustomTable’);      Attach Payload Converts payload to JSON  Sets it as the request body        restMessage.setRequestBody(JSON.stringify(payload));      Execute REST API Call Sends the request to the external/other ServiceNow instance        try {          var response = restMessage.execute();  6.Convert JSON String → JavaScript Object  The REST API response body is always a string  JSON.parse() Converts JSON string into a JavaScript object  Allows field-level access using dot notation           var responseBody = JSON.parse(response.getBody());          gs.log(“API Response: ” + JSON.stringify(responseBody));      Read Incident Data from Response Extracts incident list from API response  responseBody → full parsed object  result → main response wrapper  incidents → array of incident objects  Structure:  responseBody  └── result       └── incidents [ array ]            var incidents= responseBody.result.incidents;              Insert Data into Custom Table Loops through each incident returned          for(var i=0; i<incidents.length;i++){              var gr = new GlideRecord(‘u_add_caller_details’);    Creates new record in custom table              gr.initialize();    Accessing Fields Using Dot Notation incidents[i]. number → Fetches incident number from API response  gr.u_number → Custom table field  incidents[i].short_description → Fetches short description  gr.u_short_description → Custom table field  incidents[i] gives one incident  .number and .short_description fetch values              gr.u_number=incidents[i].number;              gr.u_short_description=incidents[i].short_description;    Inserts record into custom table              gr.insert();            }    Catches REST API errors  Logs error message to system logs        } catch (ex) {          gs.error(“REST API call failed: ” + ex.message);      }    })(current, previous);  Instance A:  This incident creation is the trigger point for:  REST API call  JSON parsing  Custom table insertion  Instance B:   ALL incidents available for the caller “Abel Tuter” in Instance B  These are the incidents that:  The Scripted REST API in Instance B queries  And returns back to Instance A in the API response  Instance A:  REST API Test Result:   REST Message executed successfully  API returned data in JSON format  Response contains:  result object  incidents array  Each incident has:  number  short_description      API Response: {“result”:{“incidents”:[{“number”:”INC0010488″,”short_description”:”0.0″},{“number”:”INC0010560″,”short_description”:”0.0″},{“number”:”INC0010232″,”short_description”:”0.0″},{“number”:”INC0010487″,”short_description”:”0.0″},{“number”:”INC0010233″,”short_description”:”0.0″},{“number”:”INC0010355″,”short_description”:”0.0″},{“number”:”INC0010356″,”short_description”:”0.0″},{“number”:”INC0010204″,”short_description”:”0.0″},{“number”:”INC0010359″,”short_description”:”0.0″},{“number”:”INC0010195″,”short_description”:”0.0″},{“number”:”INC0010292″,”short_description”:”0.0″},{“number”:”INC0010187″,”short_description”:”0.0″},{“number”:”INC0010357″,”short_description”:”0.0″},{“number”:”INC0010180″,”short_description”:”0.0″},{“number”:”INC0010181″,”short_description”:”0.0″},{“number”:”INC0010357″,”short_description”:”0.0″}]}}    Instance A:   Custom Table(u_add_caller_details)  The data shown here is not manually created  It is automatically inserted by the Business Rule in Instance A  End-to-End Flow  Incident created in Instance A  Business Rule runs after insert  Caller ID sent to Instance B via REST API  Scripted REST API in Instance B:  Queries all incidents for Abel Tuter  Instance B returns incident data as JSON  Instance A:  Parses JSON response  Loops through incidents  Each incident is inserted into:        u_add_caller_details 

Incident Synchronization Between ServiceNow Instances Using Flow Designer and Custom action 

Incident Synchronization Between ServiceNow Instances Using Flow Designer and Custom action Use Case:  When an incident is created in the source ServiceNow instance, a Flow Designer custom action triggers an outbound REST API call to create the same incident in a target instance. The target instance returns a JSON response, which is parsed and stored back in the source incident for confirmation and traceability.    Step 1: Created a REST Message  Navigated to System Web Services → Outbound → REST Message  Created a REST Message named Sample  Set the target instance URL as the endpoint  Configured Basic Authentication using a REST credential profile  Step 2: Configured HTTP Method  Added an HTTP Method named Test  Selected POST method  Set endpoint to https://myinstance.service-now.com/api/now/table/incident  Added HTTP headers:  Accept: application/json  Content-Type: application/json  Defined JSON request body using variables:  short description  caller  Id           Content:   {      “sys_id”:”${id}”,     “caller_id” : “${cd}”,      “short_description” : “${sd}”  }  Step 3 :Created a Flow  Created a Flow named Create Incident Through Integration  Configured trigger as Incident Created or Updated  Selected Incident table as trigger source  Step 4 : Created a Custom Action  Added a custom Action to the flow  Defined input variables:  sd → Short Description  cd → Caller (Sys ID)  id → Incident ID  Step 5 : Mapped Flow Data to Action Inputs  Mapped Incident Short Description to sd  Mapped Incident Caller to cd  Mapped Incident Sys ID to id  Step 6 : Added Script Step in Custom Action  Used RESTMessageV2 in the script  Called the configured REST Message and HTTP Method  Passed input variables to REST message parameters  Executed the REST call and logged the response  (function execute(inputs, outputs) {    This is a Flow Designer / Action script  inputs → values passed from Flow (incident sys_id, short description, caller)  outputs → values returned back to Flow     try {    Prevents the integration from failing silently  Any runtime error goes to the catch block          var r = new sn_ws.RESTMessageV2(‘Sample’, ‘Test’);    Calls an outbound REST Message  Sample → REST Message record name  Test → HTTP method  This REST Message points to the Target Instance       r.setStringParameterNoEscape(‘id’, inputs.id);   r.setStringParameterNoEscape(‘sd’, inputs.shortDescription);   r.setStringParameterNoEscape(‘cd’, inputs.callerId);      These parameters are sent to the target instance  Used to create the incident there  NoEscape ensures special characters are not altered    var response = r.execute();    Sends the request to the target instance  Waits for the response     var responseBody = response.getBody();   var httpStatus = response.getStatusCode();  responseBody → JSON returned by target instance  httpStatus → HTTP code (200, 201 = success)       gs.info(‘Response Body: ‘ + responseBody);   gs.info(‘HTTP Status: ‘ + httpStatus);    Logs response for debugging               var parsedResponse = JSON.parse(responseBody);   var result = parsedResponse.result;    Converts JSON string → JavaScript object  All incident details are inside result             var targetIncidentNumber = result.number;    var shortDescription     = result.short_description;    var priority             = result.priority;    var category             = result.category;    var subcategory           = result.subcategory;    var state                = result.state;    var callerSysId           = result.caller_id.value;  Reads individual values from target instance  These fields confirm incident creation success                 var grIncident = new GlideRecord(‘incident’);    if (grIncident.get(inputs.id)) {    Opens the Source Instance Incident  Uses inputs.id (source incident sys_id)         grIncident.description =             “Incident successfully created in Target Instancenn” +             “Target Incident Number: ” + targetIncidentNumber + “n” +             “Caller Sys ID: ” + callerSysId + “n” +             “Short Description: ” + shortDescription + “n” +             “Priority: ” + priority + “n” +             “Category: ” + category + “n” +             “Subcategory: ” + subcategory + “n” +             “State: ” + state;                grIncident.update();          }       Stores target incident details  Helps with traceability and auditing          } catch (ex) {          gs.error(‘Integration Error: ‘ + ex.message);      }    })(inputs, outputs);     Logs errors if REST call or parsing fails  Step 7: Executed Integration via Flow  When an Incident is created in the source instance  Flow triggers automatically  Custom action runs and sends data to target instance  REST API creates a new Incident in the target instance      Source Instance:  Before Integration Trigger:  This is the source instance incident  At this point:  Incident exists only in source  REST integration has not yet written back any data  This incident is the trigger for your Flow Designer + Custom Action  Target Instance:  This incident was not manually created  It was created by:  Inbound REST API on target instance  Triggered from source instance  Field values match what was sent in REST request  Source Instance:  After Integration Execution  The Description field is now populated automatically  REST call executed successfully  Target incident was created  JSON response was parsed correctly  Source incident was updated programmatically