INTEGRATION
- Get link
- X
- Other Apps
ServiceNow REST Integration – Full Course with ITSM Focus
1. Introduction to REST Integration
-
Definition: REST (Representational State Transfer) is a standard protocol used to integrate external systems with ServiceNow via HTTP requests (GET, POST, PUT, DELETE).
-
Why REST in ServiceNow?
-
To connect ServiceNow with external applications (e.g., Salesforce, SAP).
-
Automate ITSM workflows (Incident, Change, Problem).
-
Expose ServiceNow data via APIs.
-
Key REST Concepts:
-
Endpoints – URLs that define where to send requests.
-
Methods – GET (read), POST (create), PUT/PATCH (update), DELETE (remove).
-
Headers – Information such as
Content-Type
(e.g., application/json). -
Authentication – Basic Auth, OAuth 2.0, API Keys.
-
Payload (Body) – Data in JSON/XML format sent with POST/PUT requests.
-
Response – Output returned from the API call.
2. Types of REST Integration in ServiceNow
2.1 Inbound REST
-
External systems call ServiceNow APIs.
-
Example: A third-party monitoring tool creates an Incident in ServiceNow via REST API.
-
ServiceNow provides out-of-the-box REST APIs for tables (
Table API
) and ITSM modules.
2.2 Outbound REST
-
ServiceNow sends requests to external systems.
-
Example: ServiceNow notifies Jira to update ticket status.
3. REST API Explorer (ServiceNow Tool)
-
Path: System Web Services → REST → REST API Explorer
-
Allows you to:
-
Test REST APIs.
-
Generate sample code (cURL, Python, JavaScript).
-
Explore Table APIs, Import Set APIs, and Custom APIs.
-
4. REST Table API
-
Base URL:
https://instance.service-now.com/api/now/table/<table_name>
-
Example (GET Incident):
bashGET https://devXXXXX.service-now.com/api/now/table/incident?sysparm_limit=5
Common Query Parameters:
-
sysparm_query
– Filters data (priority=1
). -
sysparm_limit
– Limits number of records. -
sysparm_fields
– Fetch specific fields. -
sysparm_display_value
– Returns display values instead of sys_ids.
5. Steps to Create REST Outbound Integration
5.1 Create a REST Message
-
Navigate to System Web Services → Outbound → REST Message.
-
Define:
-
Endpoint URL (External API).
-
Authentication (Basic Auth, OAuth).
-
HTTP Methods (GET/POST).
-
-
Add request headers and sample request body.
5.2 Test REST Message
-
Use "Test" button in REST Message form.
-
Check response in the logs.
5.3 Use Scripted REST Integration
-
Call REST Message via script:
javascriptvar r = new sn_ws.RESTMessageV2('REST_Message_Name', 'get'); var response = r.execute(); var responseBody = response.getBody(); gs.info(responseBody);
6. Scripted REST APIs
-
Custom APIs you build for external systems.
-
Path: System Web Services → Scripted REST APIs.
-
Steps:
-
Create a Scripted REST API.
-
Define Resources (endpoints).
-
Write Scripts to handle GET/POST calls.
-
Example Scripted REST Resource:
javascript(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
var result = {};
result.message = "Hello from ServiceNow";
return result;
})(request, response);
7. ITSM Use Cases of REST Integration
-
Incident Integration:
-
Auto-create Incidents from monitoring tools like SolarWinds.
-
Example: POST Incident via REST API.
-
-
Change Management Integration:
-
Sync Change Requests with external approval systems.
-
-
Problem/CMDB Integration:
-
Fetch CI data from external CMDBs using REST GET.
-
8. Authentication Methods
-
Basic Auth: Username + Password.
-
OAuth 2.0: Secure token-based access.
-
Steps: Create OAuth Provider, Generate Token.
-
-
Mutual Authentication (MTLS): Client + Server certificates.
-
API Key: Header-based authentication (less common).
9. Error Handling
-
Check Response Codes:
-
200
– OK -
201
– Created -
400
– Bad Request -
401
– Unauthorized -
404
– Not Found -
500
– Internal Server Error
-
-
Use
try-catch
in scripted calls:javascripttry { var res = r.execute(); } catch(ex) { gs.error('REST Error: ' + ex.getMessage()); }
10. Performance Best Practices
-
Use pagination (
sysparm_offset
,sysparm_limit
). -
Fetch only required fields (
sysparm_fields
). -
Use asynchronous REST (if possible) for heavy operations.
-
Enable mid-server for on-premise integrations.
REST Integration Exam Notes (Quick Revision)
Key Points:
-
Inbound: External → ServiceNow.
-
Outbound: ServiceNow → External system.
-
Table API Endpoint:
/api/now/table/
. -
Tools: REST API Explorer, REST Messages, Scripted REST API.
-
Authentication: Basic, OAuth 2.0, Mutual TLS.
-
Code Execution:
sn_ws.RESTMessageV2
for outbound calls. -
Common Use Case: Incident auto-creation via POST.
-
HTTP Status Codes: Must memorize common ones (200, 201, 400, 401, 404, 500).
-
CMDB Integration: Use Import Set APIs if large data.
11. Suggested Real-Time Projects (for Practice)
-
Integrate ServiceNow Incident with Jira (bidirectional).
-
Push new Change Requests to an external approval system.
-
Fetch weather data from a public API and log into a ServiceNow table.
-
Build a Scripted REST API to fetch ITSM data (Incidents, Problems).
12. Learning Path for REST in ITSM (1 Week Plan)
Day 1–2: Learn REST basics (methods, headers, authentication).
Day 3: Explore REST API Explorer and test Table API.
Day 4: Create outbound REST messages and test with sample public APIs.
Day 5: Create Scripted REST APIs and handle GET/POST.
Day 6: Build an ITSM project (e.g., Incident auto-create).
Day 7: Revise exam notes and practice 5 real
A network error occurred. Please check your connection and try again. If this issue persists please contact us through our help center at help.openai.com.
You said:
ChatGPT said:
Here’s a more detailed and structured REST Integration full course with ServiceNow ITSM. I’ve expanded each section with extra details, practical tips, and real-life ITSM scenarios.
ServiceNow REST Integration Full Course (Detailed) – ITSM Focus
1. Introduction to REST Integration
What is REST?
-
REST (Representational State Transfer) is a web-based architecture that allows systems to communicate using HTTP.
-
In ServiceNow, REST is widely used to:
-
Send data to external systems (Outbound REST).
-
Receive data from external systems (Inbound REST).
-
Why REST with ITSM?
-
Automates Incident/Change/Problem creation from monitoring tools like SolarWinds, Nagios, or Splunk.
-
Synchronizes ITSM data with external systems like Jira, BMC Remedy, or Zendesk.
-
Powers Service Catalog workflows to trigger third-party APIs (e.g., provisioning servers in AWS).
2. Core REST Components
Key REST Elements:
-
Endpoint (URL):
https://instance.service-now.com/api/now/table/incident
-
Methods:
-
GET
– Retrieve records. -
POST
– Create a new record. -
PUT
/PATCH
– Update an existing record. -
DELETE
– Remove a record.
-
-
Headers: Define request format and authentication, e.g.,
Content-Type: application/json
. -
Payload (Body): JSON or XML data for POST/PUT requests.
-
Response: Returns success/error messages in JSON.
3. REST API Types in ServiceNow
3.1 Inbound REST (External → ServiceNow)
-
Example: A monitoring tool calls ServiceNow REST API to create an incident when a server goes down.
-
Prebuilt APIs: Table API, Import Set API, Attachment API, ITSM module APIs.
Sample Create Incident Request (POST):
bashPOST https://instance.service-now.com/api/now/table/incident
Headers:
Content-Type: application/json
Body:
{
"short_description": "Server Down",
"urgency": "1",
"impact": "1"
}
3.2 Outbound REST (ServiceNow → External)
-
Example: Change request approval notification sent to an external system.
-
You create REST Messages in ServiceNow to connect with other APIs.
4. REST API Explorer – ServiceNow’s Built-in Testing Tool
-
Path: System Web Services → REST → REST API Explorer.
-
Use Cases:
-
Test GET, POST, PUT, DELETE on tables.
-
Build sample queries using filters.
-
Generate sample code snippets (cURL, Python, JS).
-
5. REST Table API – The Heart of ITSM Integration
-
Base URL:
https://instance.service-now.com/api/now/table/<table_name>
. -
Query Parameters:
-
sysparm_query
: e.g.,priority=1^state=2
. -
sysparm_limit
: Restrict number of records. -
sysparm_fields
: Return specific fields. -
sysparm_display_value
: Display field labels instead of sys_ids.
-
Example:
bashGET https://devXXXX.service-now.com/api/now/table/incident?sysparm_query=priority=1
6. Creating an Outbound REST Integration
Step-by-Step Process:
-
Navigate to: System Web Services → Outbound → REST Message.
-
Fill Details:
-
Name:
Jira Integration
-
Endpoint URL:
https://api.jira.com/...
-
Authentication: Basic / OAuth.
-
-
Add HTTP Methods (GET/POST).
-
Add Request Headers:
-
Content-Type: application/json
-
-
Test the REST Message to confirm the connection.
7. Scripted REST API (Custom APIs)
When Needed?
-
If external systems need customized data or a specific workflow.
Steps to Create Scripted REST API:
-
Create Scripted REST API:
System Web Services → Scripted REST APIs → New. -
Define Resources (endpoints) and HTTP methods.
-
Add script logic.
Example:
javascript(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
var result = {};
result.incidents = [];
var gr = new GlideRecord('incident');
gr.query();
while (gr.next()) {
result.incidents.push({
number: gr.number.toString(),
short_description: gr.short_description.toString()
});
}
return result;
})(request, response);
8. ITSM REST Use Cases
-
Incident Management:
-
Automatically create incidents when a server goes down.
-
Example: Splunk POST request → ServiceNow Incident Table API.
-
-
Change Management:
-
Sync Change Request status with a DevOps pipeline (e.g., Jenkins).
-
-
Problem Management:
-
Pull logs or known errors from external systems.
-
-
Service Catalog Integration:
-
External APIs to fulfill catalog requests (e.g., AWS VM provisioning).
-
9. Authentication in REST
-
Basic Auth: Username + Password.
-
OAuth 2.0: Recommended for secure external integrations.
-
Mutual TLS: For highly secure communication.
-
API Key: Header-based token (less common in ServiceNow).
10. Advanced Concepts
-
Asynchronous REST Messages: Execute in the background using
executeAsync()
. -
Transform Maps with REST: Use Import Set API when importing bulk data.
-
MID Server: Needed for integrating with on-premises systems.
11. REST Error Handling
-
HTTP Status Codes:
-
200
– Success. -
201
– Record Created. -
400
– Bad Request. -
401
– Authentication Failure. -
404
– Not Found. -
500
– Server Error.
-
-
Code Example:
javascripttry {
var res = r.execute();
var httpStatus = res.getStatusCode();
if (httpStatus != 200) {
gs.error("REST Failed: " + res.getErrorMessage());
}
} catch(ex) {
gs.error("Exception: " + ex.getMessage());
}
12. Performance Best Practices
-
Use
sysparm_fields
to fetch only required fields. -
Use pagination (
sysparm_offset
). -
For large data, use Import Set REST API instead of direct Table API.
-
Consider batch processing for heavy integrations.
Exam Notes (Quick Summary)
-
Inbound = External → ServiceNow.
Outbound = ServiceNow → External. -
Common APIs: Table API, Import Set API, Attachment API.
-
Key Class:
sn_ws.RESTMessageV2
. -
Authentication: Basic, OAuth, Mutual TLS.
-
Common ITSM Tables:
incident
,change_request
,problem
,sc_req_item
. -
Tools for Testing: REST API Explorer, POSTMAN.
-
Error Codes: Memorize common codes (200, 201, 400, 401, 404, 500).
-
Best Practice: Use Scripted REST APIs for custom needs.
13. Real-Time REST Integration Projects
-
Project 1: Jira → ServiceNow (Incident Sync).
-
Project 2: AWS Lambda → ServiceNow Change Request.
-
Project 3: Splunk Alert → ServiceNow Incident (auto-create tickets).
-
Project 4: ServiceNow → Slack (send notification via REST).
14. Weekly Roadmap (7 Days)
-
Day 1: REST fundamentals (HTTP methods, JSON, headers).
-
Day 2: Explore Table API & REST API Explorer with ITSM tables.
-
Day 3: Create Outbound REST Message to call public APIs.
-
Day 4: Build Scripted REST API for Incident table.
-
Day 5: Practice ITSM use cases (Incident, Change).
-
Day 6: Work on real-time project (e.g., Jira → ServiceNow).
-
Day 7: Revise error handling, performance tuning, and exam notes.
DETAILS
1. 1 Inbound REST Integration (ServiceNow as a Provider)
-
Definition:
ServiceNow exposes its REST API endpoints to allow external applications to interact with ServiceNow data (create, read, update, delete). -
Key Components:
-
Table API: For performing CRUD operations on ServiceNow tables (e.g.,
incident
,problem
). -
Import Set API: For bulk data import from external sources.
-
Attachment API: For uploading/downloading attachments.
-
Aggregate API: For statistical operations (count, avg, min, max).
-
Authentication: Basic Auth, OAuth 2.0, or Mutual TLS.
-
-
Use Case Examples:
-
An external ticketing system creates incidents in ServiceNow using the
POST /api/now/table/incident
. -
A third-party HR tool fetches employee data from ServiceNow HRSD tables.
-
2. Outbound REST Integration (ServiceNow as a Consumer)
-
Definition:
ServiceNow sends REST requests to external systems and consumes their data.
This is achieved through REST Message and Scripted REST API Calls. -
Key Components:
-
REST Message Record: Configures endpoints (GET, POST, PUT, DELETE).
-
HTTP Methods: Defines operations to perform on external systems.
-
Authentication: OAuth 2.0, JWT, Basic Auth.
-
Scripted REST Messages: Customize REST calls using scripts for dynamic endpoints and payloads.
-
-
Use Case Examples:
-
Sending incident details from ServiceNow to a third-party monitoring tool.
-
Fetching weather data from an external API to display on ServiceNow portal.
-
3. Scripted REST APIs (Custom REST Endpoints)
-
Definition:
Developers create custom REST APIs in ServiceNow to expose specific data or functionality beyond the default Table APIs.
These are defined using the Scripted REST API module. -
Key Components:
-
Resources: Define endpoints like
/api/x_company/custom_api/
. -
HTTP Methods: GET, POST, PUT, DELETE defined via Scripted REST Resource scripts.
-
Security: Access controlled via ACLs, roles, and authentication.
-
-
Use Case Examples:
-
Custom API for returning filtered incident data in a specific JSON format.
-
A mobile app consuming a custom ServiceNow REST API to get change request details.
-
4. IntegrationHub REST Actions
-
Definition:
IntegrationHub provides reusable REST actions that can be called from Flow Designer.
It simplifies REST calls without needing to code REST messages manually. -
Use Case Examples:
-
Sending Slack notifications via REST API.
-
Calling Microsoft Teams APIs to create meetings from ServiceNow.
-
5. REST APIs by Scoped Applications
-
Definition:
Scoped applications can provide their own set of REST APIs.
These APIs are namespaced (e.g.,/api/x_app_scope/api_name/
). -
Use Case Examples:
-
A custom HR application provides an API
/api/x_hr_app/employee_data
.
-
6. MID Server REST Integrations (For On-Premise Systems)
-
Definition:
If an external system is on-premise and not directly accessible over the internet, ServiceNow can send REST calls via MID Server. -
Use Case Examples:
-
ServiceNow making REST API calls to an on-prem CRM system.
-
Comparison Table: Types of REST Integrations
Type | Direction | Example | Key Tool |
---|---|---|---|
Inbound REST | External → SNOW | External app creates incidents | Table API |
Outbound REST | SNOW → External | SNOW fetches weather data | REST Message |
Scripted REST API | External ↔ SNOW | Custom endpoint for ticket data | Scripted REST API |
IntegrationHub REST | SNOW → External | Slack or Teams API call | Flow Designer Action |
Scoped App REST API | External ↔ SNOW | Custom HR app API | App-specific API |
MID Server REST | SNOW → On-Prem | Call internal CRM | MID Server |
Best Practices for REST Integrations
-
Use OAuth 2.0 for secure authentication over Basic Auth.
-
Paginate API responses for large data sets.
-
Enable Rate Limiting to avoid API throttling.
-
Use Scripted REST APIs for customized, lightweight responses.
-
Test with REST API Explorer in ServiceNow before production.
1.2 REST API Explorer – ServiceNow Tool
The REST API Explorer in ServiceNow is a built-in tool designed to help developers and administrators explore, test, and generate REST API calls for ServiceNow resources (tables, records, custom APIs, etc.). It simplifies learning and using ServiceNow’s REST APIs without external tools like Postman.
1. Purpose of REST API Explorer
-
Provides a graphical interface to test REST APIs directly from the ServiceNow instance.
-
Helps generate API request code snippets in various languages.
-
Assists in understanding API methods (GET, POST, PUT, DELETE) and their behavior.
-
Eliminates the need for writing scripts to test API calls.
-
Useful for debugging, learning, and exploring ServiceNow REST endpoints.
2. Key Features
-
Interactive UI:
Allows users to select APIs (like Table API) and configure parameters, headers, and request bodies. -
Supports Multiple APIs:
Includes Table API, Attachment API, Import Set API, Aggregate API, and custom Scripted REST APIs. -
Code Snippets:
Automatically generates code snippets in languages like cURL, Python, JavaScript (Node.js), PHP, Ruby, etc. -
Request and Response Preview:
Displays API responses (JSON or XML format) to validate outputs. -
Authentication Handling:
Automatically uses logged-in session credentials or supports Basic Auth/OAuth tokens. -
HTTP Methods:
Enables GET, POST, PUT, PATCH, DELETE operations. -
Query Parameters:
Provides easy configuration for sysparm_query, sysparm_fields, sysparm_limit, and other parameters.
3. Where to Find It
-
Navigate to:
All → System Web Services → REST → REST API Explorer
4. Steps to Use REST API Explorer
-
Open REST API Explorer from the ServiceNow application navigator.
-
Select API Category:
-
Table API for record-level operations.
-
Attachment API for working with files.
-
Aggregate API for statistics.
-
Custom Scripted API if available.
-
-
Choose HTTP Method (GET, POST, PUT, DELETE).
-
Enter Table Name or Resource Path (e.g.,
incident
). -
Add Query Parameters (e.g.,
sysparm_limit=5
). -
Add Request Body (JSON) for POST or PUT operations.
-
Click Send to test the request.
-
View Response (status code, headers, and body).
-
Copy Code Snippet for your chosen language.
5. Common Use Cases
-
Test and Validate APIs before integrating ServiceNow with external systems.
-
Generate Sample API Calls for use in custom scripts, integrations, or third-party clients.
-
Explore Data in tables like
incident
,problem
,change_request
. -
Debugging issues in integration by viewing raw API responses.
6. Advantages
-
No external tools needed – integrated directly in ServiceNow.
-
Beginner-friendly, making it ideal for developers who are new to APIs.
-
Time-saving as it generates reusable sample code.
-
Helps quickly test authentication and parameters.
7. Limitations
-
Not for automation – only a testing and exploration tool.
-
Does not store previous test calls like Postman collections.
-
Cannot simulate complex API workflows or chained calls.
8. Example with Table API
GET Request
-
API:
/api/now/table/incident?sysparm_limit=2
-
Steps:
-
Select Table API.
-
Table name: incident.
-
Add parameter:
sysparm_limit=2
. -
Click Send.
-
Response: Returns 2 incidents in JSON format.
-
POST Request
-
API:
/api/now/table/incident
-
Body:
json{ "short_description": "Test incident", "urgency": "2" }
-
Response: Returns the newly created incident record details.
9. Best Practices
-
Always test APIs in sub-production instances (Dev or Test).
-
Use sysparm_fields to limit response fields for performance.
-
Use sysparm_limit to restrict records and avoid large payloads.
-
For secure APIs, prefer OAuth 2.0 authentication over Basic Auth.
10. REST API Explorer vs. Postman
Feature | REST API Explorer | Postman |
---|---|---|
Built-in to ServiceNow | Yes | No (external tool) |
Code Snippet Generation | Yes | Yes |
Collection Storage | No | Yes |
Multi-environment Support | Limited | Advanced |
Best For | Quick testing | Full API lifecycle |
1.3 What is REST API Explorer?
-
REST API Explorer is a built-in ServiceNow tool used to test, build, and explore REST APIs directly within the ServiceNow instance.
-
It is accessible without external tools like Postman, making it convenient for developers and admins to test API endpoints.
-
Navigation Path:
System Web Services → REST → REST API Explorer
Key Features:
-
Preconfigured API List
-
Provides ready-to-use API categories such as Table API, Attachment API, Import Set API, etc.
-
Users can select the desired API without manually entering URLs.
-
-
Supports CRUD Operations (GET, POST, PUT, DELETE):
-
Test and execute REST calls on ServiceNow tables directly.
-
-
Dynamic Query Builder:
-
Build sample queries with filters (encoded queries).
-
Allows adding fields, ordering, and conditions without writing query strings manually.
-
-
Sample Code Generation:
-
Automatically generates code snippets in popular languages like:
-
cURL
-
Python (Requests library)
-
JavaScript (Fetch API)
-
-
Useful for developers integrating ServiceNow APIs with other systems.
-
-
Request & Response Preview:
-
Displays the full request URL, headers, and payload.
-
Shows the response status code, response body (JSON), and execution time.
-
-
Authentication:
-
Uses the currently logged-in user’s credentials, so you can test API calls securely.
-
Use Cases:
-
Testing Table Records:
-
Perform CRUD operations (GET, POST, PUT, DELETE) on ServiceNow tables like
incident
,change_request
, etc. -
Quickly verify data retrieval or updates without external tools.
-
-
Query Building:
-
Use filters to build encoded queries (e.g.,
priority=1^state=2
). -
Test field selection (e.g., return only
number
,state
,assigned_to
).
-
-
Integration Development:
-
Generate sample code snippets to speed up external integration.
-
Copy and paste cURL, Python, or JavaScript code into your scripts or apps.
-
-
Troubleshooting:
-
Validate API endpoints during development.
-
Debug errors in request payloads or headers before using them in production.
-
Example Workflow in REST API Explorer:
-
Navigate to
System Web Services → REST → REST API Explorer
. -
Select API Category: Choose Table API.
-
Select HTTP Method: (e.g.,
GET
). -
Choose Table: (e.g.,
incident
). -
Add Query Filters: (e.g.,
priority=1
). -
Execute & View Results: See JSON response.
-
Generate Code: Copy the generated Python or cURL code for reuse.
1.4 What is REST Table API?
The REST Table API in ServiceNow allows developers to interact with ServiceNow tables (like incident
, problem
, change_request
) using standard REST methods (GET, POST, PUT, PATCH, DELETE).
It is the core API for ITSM integrations because it directly manipulates table records without requiring additional custom endpoints.
2. Base URL
The base endpoint for the Table API is:
php-templatehttps://<instance>.service-now.com/api/now/table/<table_name>
-
<instance>
– Your ServiceNow instance name (e.g., dev12345). -
<table_name>
– The target table (e.g.,incident
,problem
).
Example:
bashhttps://dev12345.service-now.com/api/now/table/incident
3. Supported Methods
Method | Action | Use Case |
---|---|---|
GET | Read | Fetch records from a table. |
POST | Create | Insert a new record. |
PUT | Replace | Replace an entire record. |
PATCH | Update | Update specific fields of a record. |
DELETE | Remove | Delete a record. |
4. Query Parameters
The REST Table API supports several query parameters to filter, limit, and control the data returned.
Common Parameters:
-
sysparm_query
– Filter records using conditions.
Example:inisysparm_query=priority=1^state=2
(Returns incidents with
priority=1
andstate=2
.) -
sysparm_limit
– Limit the number of records returned.
Example:inisysparm_limit=5
-
sysparm_fields
– Return only specific fields instead of the full record.
Example:inisysparm_fields=number,priority,short_description
-
sysparm_display_value
– Display field labels instead ofsys_ids
.
Options:true | false | all
.
Example:inisysparm_display_value=true
5. Example – GET Request
To retrieve all incidents with priority = 1:
bashGET https://devXXXX.service-now.com/api/now/table/incident?sysparm_query=priority=1
cURL Example:
bashcurl "https://devXXXX.service-now.com/api/now/table/incident?sysparm_query=priority=1" \
--request GET \
--header "Accept:application/json" \
--user 'username:password'
6. Example – POST Request (Insert New Incident)
bashcurl "https://devXXXX.service-now.com/api/now/table/incident" \
--request POST \
--header "Accept:application/json" \
--header "Content-Type:application/json" \
--data '{"short_description":"Test Incident","priority":"2"}' \
--user 'username:password'
7. Why REST Table API is Called “The Heart of ITSM Integration”?
-
Direct access to ITSM tables (Incident, Change, Problem, etc.).
-
No need to build custom APIs – ready-to-use for all tables.
-
CRUD operations (Create, Read, Update, Delete) on any record.
-
Easily integrated with external systems like Jira, SAP, etc.
-
Powerful filtering with
sysparm_query
. -
Flexible output (choose fields, display values).
1.5 Creating an Outbound REST Integration
Step-by-Step Process
1. Navigate to REST Message
-
Go to:
System Web Services → Outbound → REST Message. -
Click on New to create a new REST message.
2. Fill the Details
-
Name: Enter a meaningful name (e.g., Jira Integration).
-
Endpoint URL: Provide the external system's API endpoint.
-
Example:
https://api.jira.com/rest/api/2/issue/
-
-
Authentication: Choose the required method:
-
Basic Auth: Username/Password combination.
-
OAuth 2.0: Use OAuth profiles for token-based authentication.
-
3. Add HTTP Methods
-
Click New under HTTP Methods.
-
Provide details for GET, POST, PUT, or DELETE (depending on the integration requirement).
-
Specify the relative path (e.g.,
/issue
for Jira). -
Include the request body (for POST/PUT), e.g., JSON payload.
4. Add Request Headers
-
Add headers required by the external API.
Common examples:pgsqlContent-Type: application/json Accept: application/json Authorization: Basic <base64encoded-credentials>
5. Test the REST Message
-
Click Preview Script → ServiceNow will generate sample
RESTMessageV2
code for you. -
Use Test button on the HTTP Method record to check if the connection is successful.
-
Verify the HTTP response code (200 for success).
6. Use in Script
To call the REST message in a script (example with POST):
javascriptvar r = new sn_ws.RESTMessageV2('Jira Integration', 'post');
r.setRequestBody('{"fields":{"project":{"key":"TEST"},"summary":"New issue","issuetype":{"name":"Task"}}}');
var response = r.execute();
var responseBody = response.getBody();
gs.info(responseBody);
7. Common Use Cases
-
Sending incident data to external tools like Jira or Slack.
-
Integrating with payment gateways, ticketing tools, or custom APIs.
-
Automating data sync between ServiceNow and other systems.
1.6 A Scripted REST API in ServiceNow allows you to build custom APIs that provide more flexibility and control compared to the default Table APIs. These APIs are ideal when you need to perform complex business logic, data transformations, or interact with multiple tables before returning the response.
When is a Scripted REST API Needed?
-
When external systems require customized responses rather than direct table data.
-
When you need to implement business rules or workflows before returning data.
-
When you need to aggregate data from multiple tables.
-
When security and custom logic demand more control than standard REST endpoints.
-
For custom integrations where ServiceNow must process incoming data in a specific way.
Steps to Create a Scripted REST API
-
Create a Scripted REST API:
-
Navigate to:
System Web Services → Scripted REST APIs → New -
Fill in details like Name, API ID, and Namespace.
-
-
Define Resources (Endpoints):
-
Add a Resource Path (like
/get_incidents
). -
Define the HTTP methods (GET, POST, PUT, DELETE).
-
-
Add Script Logic:
-
Each resource can have its own script that defines how data is fetched or processed.
-
Use GlideRecord for database operations.
-
Build a JSON object for response data.
-
-
Test the API:
-
Use REST API Explorer or tools like Postman to test your custom API.
-
Example: Fetching All Incidents
javascript(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
var result = {};
result.incidents = [];
var gr = new GlideRecord('incident');
gr.query();
while (gr.next()) {
result.incidents.push({
number: gr.number.toString(),
short_description: gr.short_description.toString()
});
}
return result;
})(request, response);
Explanation of the Code:
-
GlideRecord('incident')
: Queries the incident table. -
gr.query()
: Executes the query to retrieve all incidents. -
while (gr.next())
: Loops through each record. -
result.incidents.push({ ... })
: Pushes each incident’s number and short description into the result array. -
return result;
: Returns the final JSON response.
Key Points to Remember
-
Scripted REST APIs can return custom JSON responses.
-
They are versionable (you can create multiple API versions).
-
You can apply authentication (Basic/OAuth) to secure them.
-
You can accept input parameters using
request.queryParams
,request.body
, etc.
1.7 ITSM REST API use cases for different modules:
1. Incident Management
Use Case: Automatically create or update incidents when a server or application failure is detected by a monitoring tool.
Example Scenario:
-
Tool: Splunk, Nagios, or SolarWinds detects a server downtime.
-
Action: These tools use a
POST
request to ServiceNow's Incident Table API (/api/now/table/incident
) to create a new incident record. -
Result: An incident is logged in ServiceNow with critical details like impacted CI, severity, and logs.
Sample cURL Request:
bashcurl -X POST "https://instance.service-now.com/api/now/table/incident" \
--user "admin:password" \
--header "Content-Type: application/json" \
--data '{
"short_description": "Server X is down",
"impact": "1",
"urgency": "1",
"category": "inquiry"
}'
2. Change Management
Use Case: Synchronize Change Request status with CI/CD pipelines or DevOps tools like Jenkins, Azure DevOps, or GitLab.
Example Scenario:
-
Tool: Jenkins pipeline initiates a deployment.
-
Action: Before deployment, Jenkins creates a Change Request (CR) in ServiceNow via REST. After deployment, Jenkins updates the CR status (e.g.,
Implement
→Closed
). -
Result: Deployment workflows are automatically documented, improving audit trails.
Sample cURL Request:
bashcurl -X PATCH "https://instance.service-now.com/api/now/table/change_request/<sys_id>" \
--user "admin:password" \
--header "Content-Type: application/json" \
--data '{
"state": "Implement",
"work_notes": "Change implemented by Jenkins pipeline."
}'
3. Problem Management
Use Case: Pull error logs or known issues from external monitoring or ticketing systems.
Example Scenario:
-
Tool: ELK stack logs or Jira issues.
-
Action: ServiceNow sends a
GET
request to an external API to retrieve root cause data or known errors. -
Result: Problem records in ServiceNow are enriched with accurate logs and references.
Sample cURL Request:
bashcurl "https://external-api.com/errors?component=serverX" \
-H "Accept: application/json"
4. Service Catalog Integration
Use Case: Fulfill catalog requests using external APIs (e.g., provisioning a VM on AWS, Azure, or GCP).
Example Scenario:
-
Catalog Item: "Request New AWS VM."
-
Action: When a user submits this catalog request, ServiceNow triggers an Outbound REST API call to AWS API to create the VM.
-
Result: The provisioning result (e.g., VM instance ID) is updated in the Request Item (RITM) record.
Sample Integration Flow:
-
POST /aws/api/ec2
→ Create VM -
ServiceNow updates RITM state → "Provisioned"
1. 8 Basic Authentication
-
What it is:
Uses username + password to authenticate the REST API request. -
How it works:
-
The username and password are Base64 encoded and sent in the
Authorization
header. -
Example:
pgsqlAuthorization: Basic <Base64(username:password)>
-
-
Pros:
-
Easy to set up.
-
Useful for testing or internal integrations.
-
-
Cons:
-
Less secure since credentials are sent (even if encoded) and can be intercepted if not using HTTPS.
-
-
ServiceNow Use Case:
-
Commonly used for table API calls from internal tools or scripts.
-
2. OAuth 2.0 (Recommended)
-
What it is:
A token-based authentication method, considered more secure than Basic Auth. -
How it works:
-
The client first obtains an access token from the OAuth provider (e.g., ServiceNow).
-
Every API request includes the token in the
Authorization
header:makefileAuthorization: Bearer <access_token>
-
-
Advantages:
-
Passwords are not sent with each request.
-
Tokens can expire, reducing risk if compromised.
-
Supports scopes and permissions for fine-grained access.
-
-
ServiceNow Use Case:
-
Recommended for external systems integration, e.g., ServiceNow ↔ Jira, ServiceNow ↔ Azure.
-
3. Mutual TLS (mTLS)
-
What it is:
A highly secure method where both the client and server authenticate each other using certificates. -
How it works:
-
Client and server each have a TLS/SSL certificate.
-
Both certificates are verified during the SSL handshake.
-
-
Advantages:
-
Strong security due to certificate-based trust.
-
Eliminates reliance on passwords or tokens.
-
-
ServiceNow Use Case:
-
For critical integrations where security is paramount, like financial systems or healthcare APIs.
-
4. API Key Authentication
-
What it is:
A token or key is sent in the HTTP request header (or query string) to authenticate.makefilex-api-key: <API_KEY>
-
Pros:
-
Simple to implement.
-
-
Cons:
-
Not commonly used in ServiceNow, as OAuth 2.0 is preferred.
-
-
ServiceNow Use Case:
-
Rare, but can be used for lightweight or legacy integrations.
-
Which Authentication Method Should You Use?
-
For Testing or Simple Internal APIs: Basic Auth.
-
For Secure External Integrations: OAuth 2.0 (Best Practice).
-
For Maximum Security: Mutual TLS.
-
For Lightweight APIs (non-ServiceNow): API Key (if supported).
1. 9 Asynchronous REST Messages
-
Definition: Instead of waiting for a REST call to complete, ServiceNow can execute the message in the background using
executeAsync()
. -
Use Case:
-
When the external system has slow response times, and you don't want the user to wait.
-
For bulk operations where performance is crucial.
-
-
Example:
javascriptvar r = new sn_ws.RESTMessageV2('My_REST_Message', 'POST'); r.setStringParameterNoEscape('param', 'value'); var response = r.executeAsync(); // Executes in the background gs.info('Request queued successfully');
2. Transform Maps with REST
-
When Needed?
-
When bulk data import is required from an external system into ServiceNow.
-
Example: Importing users, assets, or configuration items (CIs).
-
-
How it Works:
-
Use the Import Set API (
/api/now/import/<table_name>
). -
Data first lands in the Import Set table.
-
A Transform Map defines how the data is mapped to the target table (like
cmdb_ci
orincident
).
-
-
Key Benefit:
-
Ensures data cleansing, transformation, and mapping before final insertion.
-
3. MID Server (Management, Instrumentation, and Discovery Server)
-
Purpose:
-
Required when integrating ServiceNow with on-premises systems that cannot be accessed publicly.
-
Acts as a secure communication bridge between ServiceNow and internal network systems.
-
-
Use Case Examples:
-
Integrating with databases, Active Directory, LDAP.
-
Running orchestration tasks (e.g., starting a server).
-
-
Security Advantage:
-
MID server sits inside the customer network and pulls requests securely from the ServiceNow instance, avoiding direct inbound connections.
-
1.10 REST Error Handling
1. HTTP Status Codes
When using REST APIs in ServiceNow (or integrating with external systems), the response is indicated by HTTP status codes. These codes tell you if the request was successful or if an error occurred.
Common Status Codes:
-
200 – Success
-
The request was processed successfully.
-
Example: A
GET
request returned the requested data.
-
-
201 – Record Created
-
A new record was successfully created.
-
Example: A
POST
request created a newincident
.
-
-
400 – Bad Request
-
The server cannot process the request due to invalid syntax or missing parameters.
-
Example: A required field is missing in the JSON payload.
-
-
401 – Authentication Failure
-
Occurs when the API credentials (username/password, OAuth token, or API key) are invalid or missing.
-
Fix by checking the authentication method configured in the REST message.
-
-
404 – Not Found
-
The requested resource or table does not exist.
-
Example: Incorrect table name like
/api/now/table/incidnt
instead of/incident
.
-
-
500 – Server Error
-
A general server-side error.
-
Could be due to script errors, misconfigured integrations, or external system issues.
-
2. Best Practices for Error Handling
-
Log Errors: Use
gs.error()
orgs.log()
to capture error details in ServiceNow logs. -
Use Try-Catch Blocks:
Example in a Scripted REST API:javascripttry { var response = restMessage.execute(); } catch (ex) { gs.error('REST call failed: ' + ex.getMessage()); }
-
Check Response Status:
javascriptvar status = response.getStatusCode(); if (status != 200 && status != 201) { gs.error('Error Code: ' + status + ', Response: ' + response.getBody()); }
3. Debugging REST Issues
-
Enable REST Debugging: Go to System Diagnostics → Debugging → Debug REST API.
-
Check HTTP Logs: Review the HTTP request and response in REST Message logs.
-
Validate JSON Payload: Use a JSON validator to ensure correct formatting.
- Get link
- X
- Other Apps
Comments
Post a Comment