LogiUpSkill

Glide Aggregate

                                   Glide Aggregate It is a server-side ServiceNow API, used to perform aggregate operations like COUNT, SUM, AVG, MIN, and MAX on table records without retrieving full record data  Methods of Glide Aggregate -:  addAggregate(aggregate, fieldname)-> Adds an aggregate function like COUNT, SUM, AVG, MIN, MAX on a given field.  GroupBy-> Groups the records based on the supplied field.  Order By-> Sorts the result in ascending order.  OrderByDesc-> Sorts the result in descending order by the given field.  query()-> Executes the database query.  next ().-> Moves to the next aggregated record.  GetAggregate.-> Gives you the final calculated answer (like total count or total sum).   GetValue.-> Gives you the value stored in a field for that record.   addEncodedQuery(query String)- -> Adds a ready-made filter to get only the records you want.   setGroup(Boolean)-> Tells the system to group similar records together.   SetHavingCondition-> Filters the grouped results based on total/count/sum values.   SetLimit.-> Tells the system to return only a limited number of records.  Example -:    1). Using GlideAggregate in ServiceNow, how many incidents are grouped by category?  Output -:  2. To find number of incidents active true  Output -: 

UI Action

                                 UI Action  A UI Action is a feature used to provide buttons, links or context menu items on forms and lists. The actions enable users to update records, call workflows, run scripts, or navigate to another page.  Some Examples of UI Actions:  Submit   Approve / Reject   Close Incident   Assign to Me   Create Change Request  Example-:  Add a “Mark as VIP” button on the User form to set up a custom VIP flag.  Step 1: Navigate on Sys_User table and right click on Navigation Bar –> Configure–> UI Action  Step 2: Click on New then Add Name for New Action (Mark as VIP) –>Add table on Which we have to add UI Action (Sys_users) –> Action Name (mark_vip)  Step 3: Click on Checkbox where you have to add a Button on form or List. Step 4: Add Script for Button, add Condition and Write a Script. Step 5: Go on Users Form, open one User in Navigation bar there “Mark as VIP” Step 6: Click on “Mark as VIP” Then That user will be mark as VIP, Automatic VIP Checkbox will fill.  Context Menu in UI Action The Context Menu in a UI Action is the menu that appears when you right-click on a record in ServiceNow. Instead of showing a button on the screen, the action stays hidden until the user right-clicks.  Why use the Context Menu?  Keeps the screen clean  Hides less-used actions  Provides quick access when needed  Creating Context Menu in Form & List -:   Add Name & Click on Form & List Context Menu Check box. 

Email Script

Email Script Definition: Email Script is a server-side script used within ServiceNow notifications to dynamically generate and format email content before the email is sent. It helps retrieve record data and display it in a customized format inside notification emails. Implementation Steps: Navigate to System Notification → Email → Notification Email Scripts. Create a new Email Script and select the appropriate table (e.g., Incident). Write the script using template.print() to display required field values. Create a Notification on the same table. Configure the notification trigger condition (e.g., when Assigned To changes). Add recipients such as the Assigned User. Call the Email Script in the notification body using ${mail_script:Script Name}. Save and test the notification. Scenario: Send Incident Details to Assigned User Requirement Whenever an Incident is assigned to a user, send an email containing Incident details such as Number, Short Description, Priority, State, and Assignment Group. Implementation Steps Step 1: Create an Email Script Navigate to System Notification → Email → Notification Email Scripts Click New Name: Incident Details Script Table: Incident Step 2: Write the Email Script Step 3: Create a Notification Navigate to System Notification → Email → Notifications Click New Name: Incident Assigned Notification Table: Incident Step 4: Configure When to Send Send When: Record Updated Condition: Assigned To changes Assigned To is not empty Step 5: Configure Recipients Users/Groups in fields: Assigned To   Step 6: Add Email Script to Notification Body Step 7: Test the Functionality Open an Incident record. Change the Assigned To field. Save the record. Verify that the assigned user receives the email with all Incident details. Result: Whenever an Incident is assigned to a user, an email notification is automatically sent containing the latest Incident information generated dynamically using the Email Script.

Email Inbound/Outbound Action

Email Inbound/Outbound Action In ServiceNow, inbound and outbound is used to exchange the data between ServiceNow and external systems.For example: If an email subject contains “Network Issue”, ServiceNow automatically creates an Incident and assigns it to the Network team.  Now let’s see one example, if anyone reply from an email how it works in ServiceNow. Example Setup: In this example, we will first explain how to enable 2-Step Verification for the Gmail account that will be used. Go to Manage Your Google Account, navigate to the Security section, and activate 2-Step Verification by following the on-screen instructions. This ensures secure authentication before integrating the email.  After completing the above step, then go to create the passkey for the Gmail account.  Copy the generated passkey and temporarily save it in the clipboard or Notepad for future use.  After that, log in to the PDI and search for an Email Account. In the Application Navigator, navigate to System Mailboxes → Administration → Email Accounts and go to module.  Click on the Email Accounts module, select New, and fill the data into fields.  Aslo,  create a user account and give the user some Email address.  In the above snapshot, enter the 16-digit passkey you generated earlier into the highlighted Password field. Set the Type as SMTP, as shown in the snapshot.  What is SMTP? SMTP (Simple Mail Transfer Protocol) is the core protocol used to send emails out from the platform, handling notifications, alerts, and inbound email processing by connecting to mail servers, allowing instances to communicate with users and external systems for automated communication.  After completing the configuration, click on Test Connection to verify that the email setup is working successfully.  Now repeat the same procedure for the POP3 connection, ensuring all required details are configured correctly.  Now create an Email Inbound Action. In the When to Run section, set the Type = Reply and configure the condition as shown in the snapshot below.  Next, navigate to the Action section and configure the required conditions. You may also write a script if needed; however, if the conditions are working correctly, writing a script is not necessary.  Now, create an incident using the configured user and resolve the incident, a notification will automatically be sent and delivered to your registered email address.  Like below, you can see the Gmail you configured, the confirmation email sent through ServiceNow.  When you reply to the incident email, the message is automatically populated in the incident activity, and the incident is reopened or moved to the In Progress state. 

Logging and Debugging 

Logging and Debugging Server-Side Logging (gs)  These methods belong to the GlideSystem (gs) object and are used in server side scripting such as Business Rules, Script Includes.  1. gs.info(), gs.warn(), gs.error()  These are the modern standards. They write to the System Log [sys_log] table. They are “level-aware,” meaning you can filter your logs by severity.  Example: gs.info(“User {0} has logged in.”, gs.getUserName());  Best for: Production-ready code and general auditing.  Use gs.info() if you are building a Scoped Application or want to follow the latest ServiceNow best practices.  2. gs.log()  The “old reliable.” It also writes to the System Log but allows you to specify a Source column, which makes filtering much easier in the list view.  Example: gs.log(“Processing record”, “MyCustomApp”);  Use gs.log() only if you are working in the Global Scope and specifically want to use a custom string in the Source column for easy filtering.  Note: This is not available in Scoped Applications (you must use gs.info there).  3. gs.print()  It writes to the localhost log file on the server but does not always appear in the sys_log table UI.  Example: gs.print(“Hello from the background script”);  Best for: Running scripts in the “Background Scripts” module where you want an immediate output on the screen.  4. gs.debug()  This only logs if the system property glide.debug.log (or a specific session debug) is enabled.  Example: gs.debug(“Variable X is: ” + x);  Best for: Troubleshooting complex logic without cluttering the logs for every user.  Client-Side Logging (console)  These run in the user’s browser (Chrome, Firefox, etc.) and are used in Client Scripts and UI Scripts.  console.log() / console.debug()  These don’t write to the ServiceNow database at all. They write to the Browser Console .  console.log()   This is the standard way to output general information to the browser console. It is the most commonly used tool for “sanity checking” values while building a UI feature.  For example, print the new value while running OnChange Client script,  console.log(“The new value of the field is: ” + newValue);   console.debug()   Functionally, this is almost identical to console.log(). However, it is intended for “verbose” or “debug” level messages that you might not want to see all the time.  Example: console.debug(“Current Field Value: ” + g_form.getValue(‘short_description’));  Best for: Real-time debugging of UI behavior.  Note: Always remove these before moving code to Production, as they are visible to any tech-savvy user.  log.print()  In standard ServiceNow JavaScript, log.print is not a native global function. You might see this in specific integrations (like IntegrationHub ETL) or if a developer has created a custom log object. Usually, if you try to run this in a standard Business Rule, it will throw an error.      Method  Environment  Log Destination  Scoped App Compatible?  gs.info()  Server  System Log (sys_log)  Yes  gs.log()  Server  System Log (sys_log)  No (Global only)  gs.print()  Server  Localhost File / Script Output  Yes  gs.debug()  Server  System Log (if debug enabled)  Yes  console.debug()  Client  Browser Console  Yes    Server-Side Debugging  This applies to Business Rules, Script Includes, Scheduled Jobs, and UI Actions (server-side).  The Script Debugger   The Script Debugger is a built-in interface that allows you to set breakpoints. When the code hits that line, the system pauses execution, allowing you to inspect variable values in real-time.  How to use: Open “Script Debugger” in the Filter Navigator, set a breakpoint (click the line number in your script), and trigger the action.  Best for: Complex logic where you need to see how variables change step-by-step.  Script Tracer   The Script Tracer records every server-side script that executes during a transaction. It captures:  Business Rules  Script Includes  Script Actions  UI Actions (Server-side) It shows you the order of execution and the state of the record before and after each script ran.  Open the Tracer: Navigate to System Diagnostics > Script Tracer.  Start Tracing: Click the Start Tracer button in the top right.  Perform the Action: Go to your form (e.g., an Incident) and perform the action you want to debug (e.g., click “Update” or change the “State”).  Stop and Analyze: Go back to the Script Tracer tab and click Stop Tracer.  Review the Trace: You will see a list of every script that ran.  Session Debugging   ServiceNow allows you to toggle specific debug logs that appear at the bottom of your UI page.  How to use: Navigate to System Diagnostics > Session Debug. You can choose “Debug Business Rule,” “Debug Security (ACL),” or “Debug SQL.”  Best for: Seeing which Business Rules are firing and in what order.  Background Scripts   The Scripts – Background module is the “scratchpad” of ServiceNow. You can paste a snippet of code and run it immediately to see the output.  Best for: Testing a specific function or a GlideRecord query without having to trigger a record update.  Client-Side Debugging  This applies to Client Scripts, UI Policies, and Catalog Client Scripts.  Since client scripts run in the browser,   Console: Use console.log() to print values or debugger; in your code to force the browser to pause execution.  Sources Tab: You can find your client script in the “Sources” tab and add breakpoints directly in the browser.  The JavaScript Log & Field Watcher  ServiceNow provides a built-in “JavaScript Log” window that sits inside the platform UI.  Field Watcher: Right-click any field label and select Watch field. A pane opens at the bottom showing every script, policy, or ACL that touches that specific field.  Best for: Figuring out “What script just hid this field?” or “Why did this value change to 10?”    Tool  Environment  Use Case  Script Debugger  Server  Pausing execution and inspecting variables.  Background Scripts  Server  Testing standalone code snippets quickly.  Session Debug  Server  Watching Business Rules and ACLs in real-time.  Field Watcher  Client  Tracking why a specific field’s value/visibility changed.  Browser Console  Client  Inspecting UI errors and logging manual triggers.   

SetWorkflow and autoSysFields Methods 

SetWorkflow and autoSysFields Methods SetWorkflow   In the ServiceNow, setWorkflow() is generally used to prevent the running of business rules (or other scripts) that would be triggered by any server side updates you’re making.   setWorfklow can be used in any server-side script, including Business Rules, Script Includes, Scheduled Jobs, and (server-side) UI Actions.   The setWorkflow() method utilizes a single boolean argument of either true or false. The arguments are written as follows:   setWorkflow(false): All business rules on the table for the current scripted action (insert, update, delete, query) will be ignored.   setWorkflow(true): All business rules on the table for the current scripted action (insert, update, delete, query) will be executed.  For example, Update the Urgency to High for all active Incidents where the Assignment Group is Network, without triggering any Business Rules that would normally execute during the update.  Autosysfields  autoSysFields is used to to control whether the system automatically updates “system” fields when a record is inserted or updated.  By default, ServiceNow manages five specific fields for every record, Created by [sys_created_by],Created [sys_created_on], Updated [sys_updated_on], Updated by [sys_updated_by], Updates [sys_mod_count],  The autoSysFields () method utilizes a single boolean argument of either true or false. The arguments are written as follows:  autoSysFields(false): When autoSysFields is set to false, system field values will not be updated.  autoSysFields(true): When autoSysFields is set to true, system field values will be updated.  For example, if we use the same script that includes the setWorkflow(false) method and additionally add autoSysFields(false), the urgency field will be updated to Medium. However, the system fields (such as Updated by, Updated on, etc.) will not be modified and will remain unchanged.  Here, we can observe that the system fields Updated and Updated by are not refreshed with the latest timestamp or user name. 

How to get ServiceNow Instance

How to get ServiceNow Instance Step 1 :  Go to ServiceNow Developer Site  Open:  https://developer.servicenow.com  Visit Developer Portal :  Step 2 : Sign Up   Click on Sign Up   If you already have an account, click Log In   Fill in the required details and submit the form.    After Sign Up you will receive a message as shown below     Step 3 : Email Verification   You will receive a verification email   Click on the verification link   Once verified, click Login / Sign In   Step 4 : Initial Setup After Login   During login, you will be asked a few setup questions:   Select “Yes – I need a developer-oriented IDE” to access developer tools.   Click Next  Choose the relevant options (you may also select Other)   Accept the terms by checking the checkbox   Click Finish Setup  

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

Scripted REST API 

Scripted REST API Scripted REST API is a server-side interface in ServiceNow that lets external systems send and receive data using HTTP methods (GET, POST, PUT, DELETE) with custom logic written in JavaScript.  Table API provides access to all fields of a table (based on ACLs), which means consumers can retrieve or modify every accessible field in that table.  In contrast, Scripted REST API allows us to control and limit field access by explicitly defining which fields are exposed in the response as per business requirements.  Basically, Table API exposes all accessible fields, whereas Scripted REST API allows us to restrict and expose only required fields, improving security and performance.  Scenario 1 – Create scripted REST API to get count of records in any table in ServiceNow  Scenario 2 – Create scripted REST API to get 5 fields of incident record by passing sys id.  Solution – Navigate –> All –Scripted rest API –> New   Create record as below:  Now create one resource to get data form system as below by clicking in new   Now scroll down and test our scripted REST API by clicking on Explore REST API   Now Fill the table name as input to Api parameter e.g.- incident, problem, change_request  Now click on send button on below and scroll down to see result   Use case 2– New incidents are created daily in the target instance by synchronizing incidents from source ServiceNow instance that are in the new state and were created between yesterday and today.  To achieve above use case in source instance create Resource in same scripted REST API  Give name getIncByState , select GET HTTP method and in relative path give the state as dynamic value   Write a script which sends a response to another instance by requesting a state value.  Create an array of object and fetch incidents whose state is new and any input and add records in array of object, assign array of object to response with count like shown below.  Now, in target instance opens scheduled jobs to create a new scheduled script for fetching incidents from source instance.  Click on “new” to create new and select Run – Daily, Time zone –user system time zone and Give time value to run script on the time   Write a script in a scheduled job to fetch data in the target instance.  Now check the incident table, some records will be created in the target instance same as the source instance between yesterday and today.  Open incident table in source instance and create 2-3 incidents Now click on “Execute Now” scheduled job and see the target instance incident table. Incidents will be created in the target instance form yesterday.  This use case implements a Scripted REST API to synchronize incidents between two ServiceNow instances by automatically creating new incidents in the target instance daily. The integration filters source incidents to include only those in the new state and created within a defined time window (from yesterday to today), ensuring that only relevant and recent records are transferred. This approach maintains data consistency across instances, avoids duplicating or outdated records, and supports efficient, scheduled incident synchronization.