Table of Contents
Welcome to our JAVASCRIPT PAGE Section R
Records
- Records may be assigned to Individual users, or Groups of users. - Each record in the system, no matter what kind, has a unique number such as INC0000047.
Record Producers
- Takeaway
- A Record Producer is a specific type of Catalog Item used for creating a Task-based record such as an Incident, rather than a Request. Used to provide a better user experience than that of a regular Task-based form. The look and feel of a Record Producer is similar to that of a Catalog Item. You define a Record Producer via the Service Catalog, or from a Table record.
Roles
catalog_admin
catalog_manager
catalog_editor
- A Record Producer is a specific type of Catalog Item used for creating a Task-based record such as an Incident, rather than a request.
- Used to provider a better user experience than that of a regular Task-based form.
- The look and feel of a Record Producer is similar to that of a Catalog Item.
- You define a Record Producer via the Service Catalog, or from a Table record.
- In the front-end, Record Producers are presented as Catalog Items; this allows the Service Catalog UI to be used as a complete front-end UI (although it may make things more confusing in reality); that is, for both Catalog Items and Tasks (Incident, Change).
- A Record Producer can have its own Icon and Picture (for Desktop or for Mobile).
- Like a regular Catalog Item, a Record Producer is assigned to one or more Catalogs, and Categories.
- Variables / Questions are the inputs the user will fill out when he accesses the Record Producer. They populate fields in the underlying created record.
- For Variables of type Reference, the Type Specifications tab allows you to set “Reference Qualifier” conditions to limit the available choices.
- You can assign a Template to a Record Producer to populate fields with static information automatically.
- The Type Specification tab is only available for certain types of Variables. It allows you to set properties specific to that Type.
- Another way to create: Navigate to System Definition > Tables and open the “table record”. Under Related Links, click Add to Service Catalog.
- Similar to a Catalog Item, so it has Variables and Variable Sets. Also has Catalog Client Scripts and Catalog UI Policies.
- You use the keyword “producer” to access variables, so producer.variableName. Examples:
var sys_id_string = producer.glide_list_field;
var glideDateTime = new GlideDateTime(producer.date_field);
- A Record Producer is a specific type of Catalog Item used for creating a Task-based record such as an Incident, rather than a service catalog Request. Used to provide a better user experience than that of a regular Task-based form. The look and feel of a Record Producer is similar to that of a Catalog Item. You define a Record Producer via the Service Catalog, or from a Table record.
- Record producers live under Service Catalog - Record Producers. Table: sc_cat_item_producer
- Another way to create: Navigate to System Definition > Tables and open the record for any table. Under Related Links, click “Add to Service Catalog”. A little strange that it is not called “Create Record Producer” or something like that, but record producers are tightly associated with the Service Catalog.
- Similar to a Catalog Item, so it has Variables and Variable Sets. Also has Catalog Client Scripts and Catalog UI Policies.
- The Module Link Type for taking the user directly to a Record Producer is Module > URL (from Arguments)
- You use the notation “producer.x” to access fields set by the user on the record producer form; and you use the current object to access the record that the record producer is feeding / creating. Example:
if (producer.job_impact == false)
{
current.impact = 2;
} else {
current.impact = 3;
}
Reference Qualifiers
Reference Qualifiers - Takeaway
- A Reference Qualifier is a filter which is used to limit the choices (records) presented by a Reference Field dialog.
- A Reference Qualifier is used to create a Filter to restrict the data that is returned for a Reference Field.
- Reference qualifiers are robust and can consist of simple AND/OR conditions, inline JavaScript, or complex script includes.
- When the form loads, the filter is executed, and only the records that match the filter appear in the reference field.
- Dynamic
https://docs.servicenow.com/bundle/rome-platform-user-interface/page/use/using-lists/task/t_DynamicFilterOptions.html - GGB: I should get a better understanding of these. \\
- Reference Field
- Stores a link (reference) to a field on another table, making the records/fields in that table available to the form containing the reference field.
- For example, the Assigned to field on the Incident table is a reference to the User [sys_user] table.
- Advanced
- Advanced reference qualifiers enable you to define an inline encrypted query string OR JavaScript that evaluates to a query string.
- If you omit the initial term “javascript:” then what is expected is a string WITHOUT quotes. The entire contents of the field is assumed to be a string.
- If you DO use the term “javascript:” then what is expected is javascript which EVALUATES TO a string. Do not use the return keyword. gs.addInfoMessage does NOT work, but newline characters are OK:
- Example:
javascript:
gs.log(“Start 111”, “Phoenix”);
gs.log(current.variables.referencequalifierstring, “Phoenix”);
if (1 == 2)
{
“nameSTARTSWITHy”
}
else
{
“nameSTARTSWITHz”
}
- Encoded Query String Example:
vendor=true \\
- A JavaScript reference qualifier must return a query string that can filter the options available on the reference field.
- JavaScript Examples:
javascript:“u_idxprofilegroup=f5f39fb1dba96090b21ede46d4961995”
javascript:“u_idxprofilegroup=” + “f5f39fb1dba96090b21ede46d4961995”
javascript:new myScriptInclude().my_refqual() javascript:u_active=true^ + "u_hr_service=" + current.hr_service \\ - Important: Example of Catalog Item Lookup Select Box which is dependent on ANOTHER Lookup Select Box. This DOES WORK, magically, and dynamically, where changes to the 1 field are reflected in the other field. However, you have to not only set the "ref qual" field, as follows, but also the Variable attributes field on the "Default Value" tab, as follows. Reference qual: \\
javascript:“u_idxprofilegroup=” + current.variables.profile_group
Variable attributes:
ref_qual_elements=profile_group
See "ref_qual_elements" in the documentation here. Scroll all the way down. Service catalog variable attributes | ServiceNow Docs \\ Discussion here: \\ [SOLVED]: - Dependent variable on Catalog item using Lookup Select Box - Developer Community - Article - ServiceNow Community
- current object
- current is a JavaScript object that contains the fields and field values of the active (current) record. For forms, this is the record that is displayed (loaded) in the form. Within advanced and dynamic reference qualifiers, you can use the JavaScript current object to define filters such as javascript:“company=” + current.company. This JavaScript, within a reference qualifier, only returns the records from the referenced table that are equal to the company field value of the current record. So, if the value that appears in the Company field is Acme, the JavaScript returns all reference field records whose company value is equal to Acme (company=“Acme”). If you then bring up a record whose company value is “ViewRite”, the JavaScript resolves to company=“ViewRite.” All fields within the currently loaded form (table) are available for use with the current object. Use dot-walking to access values in a table, including the referenced table. For example, on the Incident form, the Assigned To field references the User table. To access the email address of the user, use the following syntax: javascript:“emailAddress=” + current.assigned_to.email.
Related Lists
Tables
sys_relationship (System Definition - Relationships)
sys_ui_related_list (System UI - Related Lists)
sys_ui_related_list_entry (Related List Entries) - Just controls which lists have been added to which forms in which order.
Community Article on the 2 Types of Related Lists
- Most “Related Lists” do not require manual definition. If a table A has a reference field which points to table B, when you go to “Configure - Related Lists” for table B, you will automatically see, in the “Available” list box, an entry called “B→A”.
- Adding this list to the form will simply create a window into table B with a filter automatically applied, which filters the records to only those that point back to table A. The filter may be changed, as described here:
https://docs.servicenow.com/bundle/tokyo-platform-user-interface/page/use/using-forms/task/t_CreateADefaultFilter.html
- Additional Actions (Hamburger Menu) - Configure - Related Lists… shows values from the Relationship / sys_relationship table.
- A “Related List” may be added to any form by going to Configure - Related Lists.
- A brand new Related List may be defined in the sys_relationship table. After that single record is defined, and the “Query With” field is populated with code which will return only the desired records, then the Configure Related Lists command can be used, and the relationship should show up as a choice there.
- At the bottom of the form, in the related list section, you can see which table is involved by right clicking the link to the immediate right of the filter icon and choosing Open in New Window. But that will not show you the filter that was used to create the related list. To find that, go to Filter Navigator - System UI - Related Lists. Then sort THAT list by the table that matches your given record type, and the view you are on where you are viewing your related lists. Remember that the view name is displayed to the right of the hamburger menu, or may be seen in the URL after the string “view”.
- To configure the NEW or EDIT button for a Related List on a form, open the form record, then in the Related Lists (tabs) section at the bottom of the form, with the appropriate Related List tab selected, use one of the small column hamburger menus to go to
1) Configure - UI Actions.
or
2) Configure - List Layout
or
3) Configure - List Control
Or navigate to System Definition - UI Actions, and sort by the table name of the related list. \\
- sys_relationship Table
The fields in this record can be very misleading at least in the case of this specific example…:
“Queries from table” - Where the related list items are stored after they are selected in the Pick List. This is NOT the source of those items.
“Query with” - Specifies a further filter to help identify the records to show in the SELECTED ITEMS list. Again, NOT the source of the items.
The “Advanced” options do basically the same thing, but using a query to build those same fields. Advanced did not get me anywhere.
Reports - Reporting - Data Visualization
Takeaway
- Reports organize, summarize, and present data in a meaningful way in real time, without the need to involve IT. Reports may be used to Identify trends, monitor values, look for outlying data, track work, or view progress. Most Reports support a Drilldown concept, where clicking on a report section displays a new report, containing a subset of the report's data, from the same data source. The final drilldown layer is always a list of the table records themselves. A Report may be Published, which makes it available via a URL, even to a non-ServiceNow user. A published report is NOT a snapshot in time; the report re-runs each time it is accessed. Report snapshots may be exported to PDF and may also be sent via email. A schedule may be setup to periodically email report snapshots. Reports are created in a special design tool called Report Designer.
Modules
Reports - View/Runxx Reports - Administration - Report Sources Reports - Scheduled Reports \\
Roles
report_admin Manage reports. Also, share a report to only those users with a specific Role. report_global Create global reports. Also, share a report to "Everyone". report_group Create reports that belong to a group of which the user is a member. report_publisher Make reports available on a public page. Can NOT share reports. report_scheduler Schedule reports to be delivered by email. Can NOT share reports. report_user Create reports and view reports that have been shared to the user. Can NOT share reports. \\
Reports display real-time data quickly, without the need to involve IT.
- Most reports will run quickly, provided they contain the proper filters.
- Complex reports that are data-intensive should be Scheduled, or converted to Performance Analytics so they don’t run against primary tables.
- Hidden Feature: In any list, you can right click a column label to generate a Bar Chart or Pie Chart on the fly. The report will only show the filtered data.
- After you make changes in the Report Designer, you may need to click the refresh icon (clockwise arrow) in order to see your changes.
Charts
- Bar chart - A graph which plots categorical data using bars that are proportional to values.
- Pie chart - A circular graph which plots categorical data in sections proportional to values.
- To create an on-demand chart from a list, click the Column menu (hamburger menu), then select the Bar Chart or Pie Chart menu item.
- Users must have a Report role to be able to save on-demand Bar or Pie charts.
Drilling Down
- Means to click on a report section to see a subset of the report's data in a new report.
- A Drilldown report can be a different report type than its parent, but must be for the same table or data source.
- The last level in a Drilldown is always a List Report (list).
- Limitations:
- All report types except list, histogram, calendar, control, box, and trendbox support drilling down. Drilling down is not available on reports added to forms, or reports embedded as iframes. - Drilldown reports cannot be exported to PDF files. - Only one sharing option is allowed per report. For example, it is not possible to share with Everyone based on a role and also share with specific users. - To add a Drilldown to a Report, click the “Show report structure” (network) icon in the report header.
- The “Show report structure” icon has a Badge over it which shows the current number of Drilldown levels.
- Features
- Click a Data set (value) in the Legend of most reports to temporarily remove that data from the report. Click again to restore the data.
- Publishing
- Published reports are viewable via URL, rather than using Reports - View/Run.
- Publishing a report creates a URL for others to be able to access the report, even if they are not ServiceNow users. - Share Published reports with only those who should have access to the underlying data. Anyone with the link can view the report data unless it is restricted by a Business Rule. - When the visualization is a list, a user must authenticate in order to see the records; Access controls determine whether a user can see the records. - To publish a report, open the Style tab, then Share - Publish. - To disable a report link, use Sharing - Unpublish. - After publication, click the Link icon to copy the report URL to the clipboard.
- Publishing a report allows the recipients to always see the latest data.
- Reports
- Reports organize, summarize, and present data in a meaningful way.
- Reports may be used to Identify trends, monitor values, look for outlying data, track work, or view progress.
- Filters
My Reports - Reports Created By the active user.
Group - Reports shared with a group that includes the currently active user. Global - Reports available to all users, including the currently active user. All - A combination of the other 3 categories; all reports the active user is authorized to view.
- Report Designer - ServiceNow's UI for creating and editing reports. - Tabs
Data
- The Data Source for the report. Table - A report is based on a Table or on a Data Source. With a table, you need to specify all of the conditions for filtering the data. - Data Source / Report Source - Defines a set of criteria for filtering a table, and the Report Source may be used in multiple reports. (It's like a database View) - Changes in the Data Source are reflected in all the reports that use that Data Source.
Type
- The visualization type such as bar chart or pie chart. - ServiceNow includes more than 25 standard report types (visualizations like donuts & heat maps) to display data from any instance.
Configure
- Report configuration page; this is dependent on the report type.
- Group By -
- Additional Group By - Adds a pick list to the report visualization which allows you to completely change the report display on the fly, by grouping by different values.
- Stack By -
- Aggregation -
- Max Number of Groups -
Style
- Used to control the appearance of the report.
- Important! The Share report button is on this sub-tab! And under the Share button are options to Schedule, Add to Dashboard, Export to PDF, or Publish.
- Note that even if an employee is given access to a report, if they do not have access to the Reports Module, they will not be able to run the report.
- Reports on Forms
- Reports may be added directly to a Form.
- To add a chart to a form, use Form Designer to drag the Field Type “Chart” to the desired location on the form. Once this is done, a “Configure Chart” link will appear. To edit the chart configuration again in the future, right click the chart label and choose “Configure chart”.
- Tip: Use the Chart data type sparingly. The report runs every time the form loads and can impact form load times. Developers may choose to create a view for the form which contains the chart and another which does not.
- Scheduled Reports
- See separate “Scheduled Reports *” section in this document.
- A Schedule allows a report to be shared with users and groups via email.
- Scheduled reports are automatically run at pre-defined frequency, and emailed as file attachments to a list of recipients.
- Scheduled data formats are PDF, CSV, or XLS.
- Graphical report formats are PNG or PDF.
- Tip: When scheduling reports, consider putting a link to the report in the email body. If recipients want to view the live data instead of the static data captured in the email's PDF attachment, they can easily get to the report using the link.
- If a Conditional script is used, the last line of the script must evaluate to true or false. If false, the report will not be run or emailed.
- Special Field Types
- Percent Complete
- Percent Complete fields, which accept decimal values in forms, show progress bars when displayed in lists.
- Percent Complete fields are often used to show progress towards completion for tasks or requests.
- Tip: The data type Percent Complete is not available in Form Designer. Percent Complete fields must be created in Table Editor.
- Target Thresholds - Target thresholds are a visual indicator to show progress for Percent Complete fields against a target. The progress bar color changes when threshold targets are met or exceeded. To add a Target Threshold for a Percent Complete field, Use the Advanced View to specify a target_field Attribute. Example: target_field=percent_complete_target,target_threshold_colors=0:firebrick;25:darkorange;50:gold;75:yellowgreen;90:darkgreen
- Static Report Snapshots
- Reports may be exported as PDF files in using Share - Export to PDF - Generate Now
- Reports may be emailed to a single email address using Share - Export to PDF - Send as an Email. Email sending must be enabled on the instance.
- The email sender is dev#####@servicenowdevelopers.com, where ##### = <your developer instance number>
- Visualization
- A Visualization is kind of a general term for anything visual (graphical) as opposed to plain text.
- Visualizations convey complex data, which can be difficult to describe in words, using a chart or graph. - Visualizations always show current information. (Sometimes this can actually be a problem.) - Visualizations categories and Visualizations
- Reports
- Lists
On-Demand Bar Charts and Pie Charts Percentage Complete indicators
- Forms
Embedded Charts
- Dashboards
Widgets for Reports and Analytics
Resources
- Takeaway
- Important resources to know about are the Community (Forums), Product Docs, the Customer Success Center, the Developer Portal, and NowLearning.
- Because of the scope of the ServiceNow solution, and the many applications that sit on top of it, knowing where to go for information is critical. It is important to know how to reference information quickly, as opposed to memorizing information.
- For these resources, always make a note of your Login status; Content displayed changes based on whether or not you are logged in.
250 Articles
Service Now Corporate Website
Products by Category
Product Documentation (Docs) - Products - Plugins - Release Notes - Step by Step Instructions for Functionality Community Forums (Should be logged in as "Geoffrey Bishop" under GeoffBishop@GMail.com email address.) - Post a Question (for your peers) using the Right Sidebar under "Ask a Question" (mid way down the page). - Champions
- Forums List
- Idea Portal - Allows you to see and vote on the top ideas for product enhancements.
- Knowledge Conference Artifacts
- My Articles (Content - Authored)
- User Groups
- Training and Certifications
- ServiceNow Jobs - Developer Community Customer Success Center - Attempts to curate content from all other sources. Developer Portal
- A great resource for people who are building Custom Applications on the ServiceNow platform.
- Includes Tools, community, Reference APIs, and guided labs/training.
- Coding Recommendations & Best Practices
- Plugin Testing / Experimentation
- Developer Training Courses - “Our training on the Developer Site is focused on what you need to know to develop scoped applications on the Now Platform, not what you need to pass a certification exam. That said, I think we cover most topics.” - Ben Sweetser - Developer Learning Plans
- I completed ALL 32 of these as of mid-April 2020.
- Personal Developer Instance Guide
https://developer.servicenow.com/dev.do - Access your PDI here.
- Developer Reference - Script / Client APIs / Server APIs - Scripting Technical Best Practices NowSupport / Hosted Instance (HI) Service Portal
- A business account is required for most content.
- Open a Support Case for a supported Instance
- Known Error Portal on HI
- Public Facing
- Instance Contacts, Performance, Uptime Statistics
- Upgrade your Instance
Now Learning - The single source for all of your ServiceNow course content, certification, and profile needs, no matter your role. Includes hands-on labs or simulations that guide you with immediate feedback. You can search course content by role such as Business Process Analyst. - Used this extensively for Admin training. - Simulators - ONLY available WHILE you are taking a course. When the course is done, the simulator shuts down permanently. - Low/Pro-Code Integration Developer Path - APM Implementer Path - Upcoming ServiceNow Training Courses Now Creators - Designed to help you map out a ServiceNow learning path based on who you are and where you want to go. Also helps you track your accomplishments. You can receive badges and super-badges to share your accomplishments with the world to help further your career. Super-Badges are awarded as you build experience in a specific role such as System Administrator, Implementer, Business Process Analyst, or Service Owner. The levels are Star, Pro, and Legend. Many of the badge steps do have a cost to them. - SuperBadge Workspace and My Now Profile Partners Find a Partner
- May be important for your career/job.
Partner Portal - Not available to Independent Consultants.
- Template Presentations for Customers!
- ServiceNow Adaptive Implementation Framework (SAIF)
- ServiceNow Implementation Methodology (SIM) (Already have good information on this from other sources)
Store - Pre-built functionality for purchase
- Includes certified, ready-to-deploy applications for many specific purposes.
- Allows you to Buy and Sell custom applications, or just find ideas for inspiration. zMisc Resources Gilmore Global Online Books Platform Implementation Scripting in ServiceNow Fundamentals Application Development Fundamentals Developer Learning Resources YouTube - ServiceNow Support - ServiceNow Demos W3 Schools https://github.com/
- Source Code Repository
- External Documents by Geoff
- JavsScript_2020 - Extensive notes on JavaScript
- Builder Video Series https://www.youtube.com/watch?v=hQmNIwnf4Cw
Add a sys_id column to List View
https://community.servicenow.com/community?id=community_article&sys_id=4c65b2e8db6830144819fb243996191b
Client & Server Code in One UI Action
https://servicenowguru.com/system-ui/ui-actions-system-ui/client-server-code-ui-action/
Create a many-to-many relationship
https://docs.servicenow.com/bundle/quebec-platform-administration/page/administer/table-administration/task/t_CreateAManyToManyRelationship.html
Dot Walking
https://developer.servicenow.com/dev.do#!/learn/learning-plans/quebec/new_to_servicenow/app_store_learnv2_scripting_quebec_dot_walking
Great UX Trick: Field decorations with 305 hidden icons https://community.servicenow.com/community?id=community_blog&sys_id=925eaaaddbd0dbc01dcaf3231f961940
JavaScript syntax editor
https://docs.servicenow.com/bundle/quebec-application-development/page/script/general-scripting/concept/c_SyntaxEditor.html
Platform performance
https://docs.servicenow.com/bundle/quebec-platform-administration/page/administer/core-configuration/concept/p_PlatformPerformance.html?cshalt=yes
Auto-complete for reference fields
https://docs.servicenow.com/bundle/rome-platform-administration/page/administer/field-administration/concept/c_AutoCompleteForReferenceFields.html
Reference Field Auto-Complete Attributes
https://snprotips.com/blog/2016/2/22/referencelist-attributes
EXAMPLE OF UI MACROS AND UI PAGES IN SERVICENOW
http://www.john-james-andersen.com/blog/service-now/example-of-ui-macros-and-ui-pages-in-servicenow.html
REpresentational State Transfer (REST *)
See also
REST Inbound REST Outbound
- An API which is designed to take advantage of the HTTP protocol; so there is no need to install additional software or libraries to create or use a REST API. - REST APIs are stateless because, rather than relying on the server remembering previous requests, REST applications require each request to contain all of the information necessary for the server to understand it. - The client and the server are totally independent. - All of your methods must fall into one of these types: GET POST PATCH - Replace only the specified fields. PUT - Replace the entire object with the given data and NULL out any fields which were not specified. DELETE - Example Method Names:
GET
https://[YourInstanceName].service-now.com/api/now/resource_grid/grid_metadata/%7btype%7d https://[YourInstanceName].service-now.com/api/now/resource_grid/get_messages
POST https://[YourInstanceName].service-now.com/api/now/resource_grid/usage_analytics
https://[YourInstanceName].service-now.com/api/now/resource_grid/resourceplan/%7boperation%7d - I believe that the word “representational” means that all of the necessary information is included; so no state information is left behind (maintained) by the server. - For integrating to ServiceNow, there are basically 3 main REST API approaches to be aware of, as follows: Inbound to ServiceNow
Option 1 Use an existing API such as the Table API for writing to tables, or use an existing Integration Hub Spoke. Use the REST API Explorer to Test and to generate client-side code in a number of different languages. Option 2
Build your own “Scripted REST API” using Studio. Define “Resources”. Populate Response object in a Resource Script process() function.
Use the REST API Explorer to Test and to generate client-side code in a number of different languages.
Outbound from ServiceNow
Option 1
Configure REST Message records using an easy form-based UI. Configure information about Endpoint, Authentication, Headers, and Methods.
Invoke the pre-configured Message from server-side script using the RESTMessage object. Use the JSON API methods parse() and stringify()
REST Inbound / REST API * / Inbound Requests (Out of the Box)
- Takeaway - Web services make it possible for applications to connect to other software applications over a network allowing an exchange of information between the provider (server) and consumer (client). ServiceNow provides three important REST APIs, one for Tables, one for Attachments, and one for Emails. ServiceNow's REST API Explorer is an application used to build and test inbound API requests to a ServiceNow instance. It creates code samples in several languages, for use in integrating with ServiceNow's APIs. Three different ways of passing in information include Request Header, Path Parameters, and Query Parameters. A REST API Response includes an HTTP Status Code, a Response Header, and a Response Body. Never build a new Integration before first looking for existing integration methods or existing components which may be turned on or purchased. - Modules
REST - REST API Explorer System Diagnostics - Session Debug - Debug SQL System Diagnostics - Session Debug - Debug Security
System Web Services - REST - CORS Rules - Roles rest_api_explorer - Web services make it possible for applications to connect to other software applications over a network allowing an exchange of information between the provider (server) and consumer (client). - To integrate with any web service, developers need to know: - Endpoints - Methods - Variables ServiceNow APIs (Out of the Box) REST API reference - “Table” API - Create, read, update, and delete records from a table. The most important API! - “Import Set” API - Another very important API with some advantages over the “Table” API. See separate section of this document.
- See “Import Set API” section of this document.
- Attachment API - Upload and query file attachments. - Email API - Send and receive email messages using REST. REST API Explorer - ServiceNow's REST API Explorer is an application (module within ServiceNow) used to build and test inbound API requests to a ServiceNow instance.
- Get to it via Filter Navigator - System Web Services - REST - REST API Explorer
- Geoff did a quick POST example against the Incident table, and just input a single field, “short description”, and returned 3 fields (sysparm_fields): number, short_description, and sys_id. Filed to input is specified in the Request Body section using the “Builder” tab. - Used to build REST Requests for integrations. - Caution: The REST API Explorer interacts directly with the tables on your instance. The REST API Explorer can delete, update, and insert records. - Namespace
- Global
- now - a REST API provided by ServiceNow. Includes the important “Table API”.
- private_scope_name - An API for a Scoped Application.
- API Name - The name of the API you will be accessing. - API Version - The version of the API you will be accessing; or you may chose “latest”. - Method - The specific function within the selected API that you wish to test, such as GET, POST, PUT, PATCH or DELETE.
Code Samples - The REST API Explorer creates code samples in several languages, for use in integrating with ServiceNow's APIs. - Languages include: ServiceNow Script, cURL, Python, Ruby, JavaScript, Perl, Powershell.
- Request Parameters:
- Path Parameters
- Enclosed in curly brackets {} in the endpoint URL.
- The values specified here are appended onto the endpoint URL (path) when the request is sent.
- Query Parameters
These are appended to the URI after the “?”, in a name=value format. Often used to filter, sort, or specify the output format.
Types of Values: Encoded queries
- Encoded query syntax is not documented, and encoded queries are not easy to create manually, so it's best to use the ServiceNow Platform UI Filter Builder to build these; then right click the resulting breadcrumbs, and select “Copy query”.
Field names Dot walking is allowed in field names. Some field names accept a comma separated list of values. Be sure to use the field Names, and not the field Labels. true/false/all - This is used for Reference Fields returned by a REST call, and specifies the format/contents of the returned value. true - Returns the human readable display value false - Returns the 32 character sys_id all - Returns both the sys_id (in a variable named "value") and the display value (in a variable named "display_value").
sysparm_exclude_reference_link - Set to true to have reference fields returned as strings rather than objects with hyperlinks. sysparm_fields - If the sysparm_fields query parameter has no value, all fields are returned for the record.
- Request Headers
- Define the Format of the Request and Response.
- Request format:
application/json
application/xml text/xml X-WantSessionNotificationMessages - Set to true to return notifications that have not already been consumed for the session. X-WantSessionDebugMessages - Set to true to return session debug logs. (Enable Session Debug in the instance also.) - Response format - Authorization - ServiceNow API Response HTTP status code 1xx - Informational 2xx - Success 3xx - Redirection 4xx - Client Error 5xx - Server Error Response Headers Include information such as the Content-Type (application/json) Response Body This is the target data, returned by the ServiceNow web service provider. Reference fields - The database value is a sys_id. The display value is the human-readable name. Date fields - The database value is in UTC format, while the display value is based on the user's time zone. Choice fields - The database value will normally be a number, but the display value will be more descriptive. Currency fields - Converted to the local currency based on the user's locale.
- Security Considerations
- Strategies
- Create a user specifically for inbound requests.
- Users with the “Web service access only” option set on their user record cannot log into the ServiceNow UI. This option allows the user credentials to be used only to authorize API connections. - The API request user must be granted the roles necessary to access the records requested by the API requests.
- Entirely disallow web service access to tables.
- System Definition - Tables - “Allow access to this table via web services”
- Disable web service access to tables with sensitive data unless web service access is required.
- Note: The REST API Explorer ignores this setting, and may still interact with the table even if this option is false!
- Create CORS Rules.
- Cross-Origin Resource Sharing (CORS) rules control which domains can access specific REST API endpoints.
- System Web Services - REST - CORS Rules
- CORS Domain Requirements
- Note: CORS Rules cannot be tested using the REST API Explorer.
- Spokes which are already included in ServiceNow Integration Hub subscriptions (Starter, Professional, and Enterprise):
https://www.servicenow.com/content/dam/servicenow-assets/public/en-us/doc-type/legal/snc-addendum-integrationhub.pdf
REST Inbound / REST API * / Scripted REST APIs * (Custom APIs) (SRAPI)
- Takeaway - A Scripted REST API allows an external application to invoke resources inside of ServiceNow, and execute Script. In many cases, built in ServiceNow APIs provide the methods developers need to integrate to ServiceNow. In other cases, custom APIs must be developed. Use the REST API Explorer, or a third-party application to test Scripted REST APIs. A Scripted REST API involves the definition of the following: HTTP Method (Get, Post), Query Parameters, Request Headers, Resources, and Response Types. A Scripted REST API may require a consumer to pass an Access Control check. A Resource Script is the meat of the API and populates properties of the Response object. - Modules
Studio - Inbound Integrations - Scripted REST APIs Performance Analytics - Dashboards
- Note: Every time you create a SRAPI you have to account for the customization and the support needed for that custom endpoint. Make it too generalized, and it’s not going to be functional to every person's needs, make an endpoint per application/user and you quickly end up with 50+ SRAPIs doing similar things. - Scripted REST Services allow developers to create their own APIs on the Now Platform. - In many cases, the built in ServiceNow APIs provide the methods developers need to integrate to ServiceNow. In other cases, custom APIs must be developed.
- Important Built-In APIs include:
Service Catalog API in the sn_sc namespace.
Table API in the now namespace. Import Set API in the now namespace.
- Use the REST API Explorer, or a third-party application to test Scripted REST APIs. - Scripted REST APIs do not directly perform actions. They are collections of “Resources”. Resources are the actions third-party applications invoke. - Content Negotiation
- By default, the supported formats for both the Request and the Response are the following:
application/json
application/xml text/xml
- Definition
- Scripted REST APIs define:
- Query parameters
- API Documentation - Request headers - Request and Response types - Resources - Documentation
- A Documentation page may be constructed for the API using Create Application File - Forms & UI - UI Page. Category = General.
- The hyperlink of the UI page should be pasted into the Documentation tab of the Scripted REST API application, in the “Documentation Link” field.
- Headers List of HTTP Header Fields - A REST Request Header contains parameters / metadata that define the HTTP(S) interaction. - Commonly used REST headers include:
- Authorization
- Accept
- Content-Type
- Query Parameters
- Control what information consumers of the API can pass in, in the request URL.
- By convention, query parameters are lowercase and use underscores in place of spaces.
- Resources
- A REST Resource represents a set of data such as a record, a change to a record, or a calculation based on one or more records.
- A Resource consists of:
- HTTP method (Relative path including path parameters)
- Resource path - Security - Allowed response format type - Resource documentation - Request header associations - Query parameter associations - Script
- Each Resource has at least one URI and is associated with one of these HTTP methods:
- GET
- POST
- PUT
- PATCH
- DELETE
- Has a “Relative Path” which may contain parameters enclosed in curly brackets { }. The Relative Path is appended to the Base API Path defined in the Scripted REST API itself. A consumer passes path values for the parameters as a part of the service's URL. - To create a Resource, from the Scripted REST API (in studio), use the Resources related list.
- By default, resources require authentication and authorization.
- Resources can override settings inherited from the Scripted REST API.
- The Resource Documentation Short Description field value appears in the REST API Explorer when the resource is selected. Use this field to provide useful information to developers using the resource.
- To associate a request header with a Resource, use the “Request Headers Associations” related list.
- To associate a query parameter with a Resource, use the “Query Parameters Associations” related list.
- Resource Script - A resource script is a server-side JavaScript that creates and populates properties on the response object. The response object is returned to the application that invoked the resource. - The template's process function, known as a self-invoking or immediately invoked function expression, is automatically invoked when a Resource is accessed. The Request and Response objects, which are passed to the process function, are automatically created. - RESTAPIRequest - Provides access to data from the Request.
- Properties:
- body
- pathParams - queryParams - queryString - uri - url - headers - Note, header property names are lowercase even if the property is defined in the API using uppercase characters. - getHeader() - getSupportedResponseContentTypes() - RESTAPIRequestBody - Allows access to the body content of a scripted REST API Request.
- Icons in the properties list identify the data type of the property!
- 0 - Object
- S - String
- F - Function
- properties/functions:
data
dataStream dataString hasNext() nextEntry()
- RESTAPIResponse - Allows for the construction of a Response to a scripted REST API Request.
RESTAPIResponse Object Documentation - Populate the body object to return data to the application. - Access is available to the headers, query parameters, and path parameters. - properties/methods: getStreamWriter() setBody() setContentType() setError() setHeader() setHeaders() setLocation() setStatus()
- RESTAPIResponseStream - May be used to write directly to the scripted REST API response stream instead of using other APIs.
RESTAPIResponseStream Object Documentation - Error Objects - Predefined: - BadRequestError - Status Code = 400. Description = Error in the request, such as incorrect syntax.
- NotFoundError - Status Code = 404. Description = Requested resource is not available. - NotAcceptable Error - Status Code = 406. Description = The Accept header value is not allowed. - ConflictError - Status Code = 409. Description = There is a conflict in the request. - UnsupportedMediaTypeError - Status Code = 415. Description = The requested media type is not supported.
- Example:
return new sn_ws_err.NotFoundError('The resource you requested is not part of the API.'); - Security
- A Scripted REST API may require a consumer to pass an Access Control check.
- Versions
- By default, API versioning is disabled.
- Enabling versioning allows developers to test and deploy changes without impacting existing integrations from web service consumers.
- Versioning is enabled at the Scripted REST API level, via the Enable Versioning Related Link.
- When versioning is enabled, Resource URLs contain a version number. To prevent breaking existing integrations when enabling versioning, make version v1 the default. - Once versioning is enabled, it cannot be disabled. - To add a new version to an API, click the “Add new version” related link. - Create documentation for each version of the API. - API Analytics
- The “System Web Services - Usage by API” dashboard displays analytic data on a per API basis.
- Statistics Included:
- API Usage by Resource (Last 30 Days)
- API Usage by Method (Daily)
- REST API Usage by Version (Daily)
- API Usage (Monthly)
REST Outbound * Integration / Outbound Requests
- Takeaway - ServiceNow stores details on how to consume external REST web services in a REST Message record. A REST Message may be configured using a form-based UI. The REST Message includes details about the Endpoint, Authentication, HTTP Headers, and HTTP Methods. Once an outbound REST Message is configured and tested, it can be invoked from any server-side script. A REST Method defines the Verb to use, such as GET or POST, the exact Endpoint, a MID Server, if necessary, HTTP Header Name/Value pairs, and HTTP Query Parameters. - Modules
System Web Services - Outbound - REST Message
System Logs - Outbound HTTP Requests sys_rest_message sys_rest_message_fn - An Outbound REST call may be used for many scenarios, such as the following
- A REST call from ServiceNow to a web service to get updated stock prices for company records.
- A REST call from ServiceNow to a ServiceNow instance to get user details. - A REST call from ServiceNow to a language translation web service to translate a knowledge article. - A REST call from ServiceNow to a vendor to get updated product information. - A REST call from ServiceNow to a weather API to get updated weather information at a customer site. - Outbound Rest Messages - ServiceNow stores details on how to interact with external web services through REST in a REST Message record. - Use an Outbound REST Message to define, test, and debug an interaction with a third-party web service provider. - The REST Message record includes: - Endpoint - Authentication - HTTP Headers - HTTP Methods (related records) - Outbound REST Messages allow developers to test web services and view the response body. - Once an outbound REST Message is configured and tested, it can be invoked from any server-side script.
- Example:
var r = new RESTMessage('Yahoo Finance', 'get'); “Yahoo Finance” defined in table “sys_rest_message” r.setStringParameter('symbol', current.stock_symbol); var response = r.execute(); Make the actual REST API call. var body = response.getBody(); if (response.getStatusCode() == 200) {
current.stock_price = body; current.update();
} - Fields
Name - A descriptive name for the REST Message. Used when invoking the message from a Script. Endpoint - May include variables in the format ${variable} Authentication type - Outbound REST supports two authentication types: - No authentication
- Basic - Username and Password
- A basic Auth Profile consists of a Name, a Username, and a Password.
- To edit a Basic Auth Profile, type “sys_auth_profile_basic.list” into the Application Navigator.
- Use Mutual Authentication - Used to require the web server provider to authenticate also.
- A protocol/socket level authentication (as opposed to an application-level method of authentication).
- Not available for web services that use a MID server.
- Can be used in conjunction with other authentication mechanisms.
- To define a Mutual Authentication Profile use the Application Navigator to open System Security - Protocol Profiles.
- OAuth 2.0 - Uses an OAuth provider and profile. - OAuth is an Internet standard that provides users with access to APIs without giving them a password.
Setting Up OAuth HTTP Headers - List of HTTP Header Fields
- Scripting REST Messages - The benefit of an Outbound REST Message is that it allows an API interaction to be configured, tested, and debugged using a form-based UI. - It is not Necessary to use a REST Message record. You can define the entire REST message in Script using the sn_ws.RESTMessageV2() object. - Methods involved in Scripting a REST message include:
- setEndpoint()
- setHttpMethod()
- setQueryParameter()
- setStringParameterNoEscape()
- setRequestHeader()
- setLogLevel()
- setStringParameter()
- setRequestorProfile()
- setMutualAuth()
- HTTP Methods
- Define the action to take for a resource, such as retrieving information or updating a record.
- Verbs:
- GET
- POST
- PUT
- PATCH
- DELETE
- Endpoints
- To configure the HTTP method endpoint, refer to the web service provider's API documentation.
- Authentication
- Normally inherited from the outbound REST Message (parent).
- Request
- MID Server - Used when the web service to be consumed is on an internal company network, not accessible from the Internet.
- HTTP Headers
- Define name value pairs here.
- List of HTTP Header Fields
- HTTP Query Parameters
- Provide names and values here.
- Appended to the Endpoint at runtime, after the “?” symbol.
- Often used to filter, sort, or specify the output format.
- Related Links
“Preview Script Usage” - Generates a server-side JavaScript code stub to invoke the API!
- You may need to modify the script logic for the Catch block.
- The RestMessageV2 API sends outbound REST messages using JavaScript.
- The RESTMessageV2 API is part of the sn_ws (Web Service) namespace, accessible to all Scopes. - Use JavaScript string methods, such as substring(), substr(), or indexOf(), to extract data from the responseBody variable. - JSON
- When working with a json response, use the JSON API , which converts a JSON formatted string to a JavaScript object.
- Use the parse() and stringify() methods.
- XML - When working with an XML response in a privately scoped application, use the XMLDocument2 API to extract data from the response body. - Debugging
- Steps
1) Look at the test results page. What does the HTTP Status field say? Is it 200/Success? What does the Response field say?
2) System Logs - Outbound HTTP Requests. After setting the log level, Test Again to generate the log.
Roles - Role-Based Access
- Takeaway - Access to features and capabilities in ServiceNow is restricted to users with certain Roles. For example, each Application, Application Menu, and Module specifies a Role that a user must have in order access it. Roles and Users are both assigned to Groups and if a User is in a Group which has a particular Role assigned, the User gets that role. Groups may be linked in a Parent/Child relationship. When this is done the Child Group automatically inherits any Roles assigned to the Parent. Roles may also be assigned to other Roles in a Parent/Child relationship; therefore a user with the parent Role automatically is granted the child Roles. - Modules Studio - “Create Application File” - Access Control
- User Administration - Users
- User Administration - Groups
- Base System Roles - Roles in ServiceNow are loosely grouped into Requestor roles and Fulfiller (Provisioner) roles. Fulfiller roles affect subscriptions (pricing). - Roles control access to features and capabilities such as Applications, Modules, Actions, and some Data. - ServiceNow is Role-Based. A user may have 0 to many roles. Even a user with No role can do many things such as Change his Password take Surveys, or Request Services from the service catalog. - User - An individual who has been granted access to your ServiceNow instance. - Group - A set of users who share a common purpose. - Users are typically assigned to one or more groups. - Groups allow roles to be assigned to multiple users all at once, as a batch. - Can have a parent group. The child group inherits the roles of the parent. - Roles and Users are both assigned to Groups. It is Not considered a best practice to assign a role directly to a user. - Access To / Visibility Of an application in the Application Navigator is controlled by the Application's “User role” setting. - Access to an Application can also be set at the Application Menu level. Go to Application Menus - [Application Name] - Access to an Application's modules may be restricted by role. Go to Modules - [Module Name] - For users with No Role to be able to see an application, both the Application and Module menus must have No Role assigned. - Applications commonly have an application admin role in addition to an application user role. Application admins have access to modules that users do not. - In Developer Studio, you create a new Role via “Create Application File” - Access Control. This may not be very intuitive. - Roles are scoped application files so they may be managed in Developer Studio, however Groups are not. Groups are managed in the ServiceNow instance.
Root Cause Analysis (RCA)
-
Rows Per Page / Records Per Page (100) System Properties - UI Properties - Items per Page (Number of Items) - This controls the available options for users to configure how many items show up in a List View. - The user gets to this setting by going to any list view, and then in the List Controls menu (hamburger menu at the very top left), by selecting Show - X Rows Per Page.
Reference Field Record Selection Dialogs
- Articles Auto-complete for reference fields Auto complete in Reference Type Variable https://snprotips.com/blog/2016/2/22/referencelist-attributes - Typing Directly into the Reference Field (AutoComplete * / TypeAhead *) - By default, a reference field auto-completes as the user types data into the field. - A field inherits and uses the referenced table's auto-complete attributes unless the field has its own value for the same attributes. You can define the attributes for a table, and they will affect every form that references that table. - Filtering Out Records, for example, to show only Active values… - Options 0. Add a reference Qualifier to a base table such as the Task Table. Or add a reference qualifier to a Dictionary Override on a child table such as the Incident table. 1. Add a “Reference Qualifier” to Each reference field (form field) where the functionality is wanted. 2. Add an “On Select” business rule that prevents ANY query from selecting certain types of records, unless the user has specified roles. This must be done carefully, because it will affect literally ALL queries that run against the table. - Specifying which columns appear - To have Consistent behavior across all fields which reference a particular table, such as the CMDB_CI table, what you should do is: A) REMOVE any Auto Completer (ac) attributes which may be set directly in referencing forms or catalog items, and B) Configure the Auto Completer behavior on the referenced table itself. You do this in the sys_dictionary entry representing the entire table (as opposed to an individual column). Navigating to this is a little tricky, and is done as follows. 1) Open up the list view for the table, such as cmdb_ci.list. 2) From any column menu, choose Configure Dictionary. 3) Sort by Column Name. 4) Open up the one record with a Blank column name, and a data type of “Collection”. 5) Finally, set the Attributes field (after it is configured to appear on the form), or use the Attributes Related List.
Attributes Field Example: ref_ac_columns=u_env_class;sys_class_name;serial_number, ref_ac_columns_search=true,
ref_ac_display_value=true, ref_auto_completer=AJAXTableCompleter
Related List Example: Attribute Value (Example) Reference auto completer AJAXTableCompleter Reference auto completer columns email Reference auto completer columns search true Reference auto completer order by name
OR, you can use the Dictionary Module (table sys_dictionary) to navigate to this, but be sure you filter by table == whatever, and then sort by column name.
- Notes
- ref_auto_completer - Specifies the name of the client side JavaScript class that creates the drop down dialog.
- AJAXReferenceCompleter - Displays matching auto-complete choices as a drop-down choice list (single column of values only). The list only displays the reference table's display value column. Reference fields automatically use this class if there is no other auto-completion class specified. - AJAXTableCompleter - Displays matching auto-complete choices as rows in a table (multiple columns shown). The table displays the reference table's display value column and any columns listed in the ref_ac_columns attribute. - ref_ac_columns - Specifies the list of reference table columns to display. Separate column names with a semi-colon. Example: ref_ac_columns=user_name;email;sys_created_on - Allows auto-complete to match text from the user_name, email, and sys_created_on columns. ref_ac_order_by - Specifies the reference table column that sorts the auto-completion choices. Example: ref_ac_order_by=name sorts the auto-completion choices alphabetically by name.
- Quirks
It is NOT currently possible to specify column headers for the Auto-Complete / Type-Ahead dialog. - To configure AutoComplete / TypeAhead for a specific Form Field or Catalog Item Variable… For Incidents Form Fields… Right click the Reference Field and select Configure Dictionary (table “sys_dictionary”). Then on the main form configure the Variable Attributes as follows: ref_contributions=task_show_ci_map;show_related_records,ref_auto_completer=AJAXTableCompleter,ref_ac_columns=serial_number For Catalog Item Variables…
Find the Catalog Item (Service Catalog - Maintain Items). Then, find the appropriate Question (Variable)… On the form for the variable, (table "item_option_new"), on the Default Value tab, configure the Variable Attributes value as follows:
ref_auto_completer=AJAXTableCompleter,ref_ac_columns=sys_class_name;serial_number;u_env_class,ref_ac_columns_search=true
- Using the Magnifying Glass Button (Full Search Dialog) - Filtering Out Records - Options 0. Add a reference Qualifier to a base table such as the Task Table. Or add a reference qualifier to a Dictionary Override on a child table such as the Incident table. 1. Add a “Reference Qualifier” to Each reference field (form field) where the functionality is wanted. 2. Add an “On Select” business rule that prevents ANY query from selecting certain types of records, unless the user has specified roles. This must be done carefully, because it will affect literally ALL queries that run against the table.
- Quirks
For the query parameters which were setup, it is not currently possible to either 1) Display them, or 2) allow the user to Remove / Change them. (The most common use-case is that you want to force the user to see only the subset of records you have specified.)