ServiceNow REST API integrations enable seamless data exchange between ServiceNow and external systems through standardized HTTP endpoints. These integrations solve critical business problems like real-time data synchronization, automated workflows, and system consolidation for IT operations teams, developers, and integration specialists. REST APIs provide the most flexible integration method, supporting custom authentication schemes and complex data transformations that proprietary connectors cannot handle. ServiceNow supports bi-directional REST API communication through outbound REST messages for sending data to external systems and inbound scripted REST APIs for receiving data, with integrations typically triggered by business rules, scheduled jobs, or webhook events and managed through the System Web Services application menu.
Prerequisites
- •ServiceNow instance with admin or rest_service role privileges
- •External system with REST API endpoints and valid authentication credentials
- •Network connectivity between ServiceNow instance and target REST API endpoints
- •Understanding of JSON data structures and HTTP status codes
- •Basic knowledge of ServiceNow scripting and GlideRecord operations
- •Access to ServiceNow System Logs application for troubleshooting outbound requests
- •MID Server installation if integrating with on-premises systems behind firewalls
Architecture Overview
ServiceNow REST API integrations utilize native platform capabilities including RESTMessageV2 for outbound calls and Scripted REST APIs for inbound requests, without requiring dedicated Integration Hub spokes. Authentication credentials are securely stored using Connection & Credential Aliases in the Connections & Credentials application, supporting multiple authentication methods including OAuth 2.0, API keys, and basic authentication. Data flows can be bi-directional with outbound REST messages triggered by business rules or scheduled jobs sending ServiceNow data to external systems, while inbound scripted REST APIs receive data from external systems to create or update ServiceNow records. MID Servers are only required when integrating with on-premises systems that are not accessible from the ServiceNow cloud instance due to firewall restrictions. Rate limiting considerations include both ServiceNow's outbound request throttling (default 100 concurrent requests) and the target system's API quotas, which must be monitored through System Logs and configured appropriately in REST Message retry policies.
Sourdough: ServiceNow Monitoring and Analytics
A Chrome extension for ServiceNow Admins and Developers with essential tools, analytics, graphs and monitoring features.
Free to install. Pro $5/month after a 14-day no-card trial.
Pro requires the ServiceNow admin role. Upgrade inside the extension.
Implementation Steps
Create Connection and Credential records for REST API authentication
Navigate to Connections & Credentials > Credentials and click New to create a credential record matching your target system's authentication method. For API key authentication, select 'API Key Credentials' type and enter the API key value in the API Key field, setting the key name as required by the target system (commonly 'X-API-Key' or 'Authorization'). For OAuth 2.0, select 'OAuth 2.0 Credentials' and configure the OAuth URL, client ID, client secret, and scope parameters provided by the external system. Save the credential record and note the generated sys_id, then create a Connection record by navigating to Connections & Credentials > Connections, referencing your credential and setting the connection URL to your REST API base endpoint.
Configure REST Message record for outbound API calls
Navigate to System Web Services > Outbound > REST Message and click New to create a REST Message record. Set the Name field to a descriptive value like 'External System Integration', enter the Endpoint URL for your REST API base URL, and select the appropriate Authentication type matching your credential configuration. In the Authentication tab, reference the Connection record created in step 1 by selecting it in the Connection field. Configure default HTTP headers in the HTTP Request tab if required by your API, such as Content-Type: application/json or Accept: application/json. Test the connection by clicking the Test link to verify authentication and network connectivity work correctly.
Create HTTP Methods for specific REST API endpoints
Within your REST Message record, scroll to the HTTP Methods related list and click New to create specific methods for each API endpoint you need to call. Set the HTTP method (GET, POST, PUT, DELETE) and the Endpoint URL relative path, such as '/users' or '/incidents/{id}' for parameterized endpoints. Configure the Content field with a sample JSON payload for POST/PUT methods, and set up HTTP headers specific to this endpoint if different from the default REST Message headers. Use variable substitution syntax like ${variable_name} in both the endpoint URL and content body to make the method reusable with different parameters. Save each HTTP Method and use the Test functionality to verify it works with sample data before proceeding to script integration.
Implement outbound REST API calls using RESTMessageV2
Create server-side scripts (Business Rules, Script Includes, or Scheduled Jobs) to execute REST API calls using the RESTMessageV2 API. Instantiate a new RESTMessageV2 object with your REST Message name and HTTP method name, then use setStringParameterNoEscape() to set any endpoint URL parameters and setRequestBody() for POST/PUT request payloads. Execute the request using the execute() method and capture the response using getBody(), getStatusCode(), and getErrorMessage() methods for proper error handling. Always implement try-catch blocks around REST calls and log both successful responses and errors to aid in troubleshooting, storing response data in appropriate ServiceNow tables or triggering follow-up workflows based on the API response.
var rm = new RESTMessageV2('External System Integration', 'POST User');
rm.setStringParameterNoEscape('user_id', current.sys_id);
rm.setRequestBody(JSON.stringify({name: current.name, email: current.email}));
try {
var response = rm.execute();
var statusCode = response.getStatusCode();
if (statusCode == 200 || statusCode == 201) {
gs.log('User created successfully: ' + response.getBody());
} else {
gs.error('API call failed with status ' + statusCode + ': ' + response.getErrorMessage());
}
} catch (ex) {
gs.error('REST call exception: ' + ex.getMessage());
}Create Scripted REST API for inbound webhook processing
Navigate to System Web Services > Scripted Web Services > Scripted REST APIs and click New to create an API for receiving data from external systems. Set the API Name, API ID (URL path), and Namespace, then configure the Security requirements such as requiring authentication or allowing anonymous access based on your security requirements. Create HTTP method resources (GET, POST, PUT, DELETE) in the Resources tab, defining the specific URL patterns and request/response handling logic for each endpoint. In each resource script, use request.body.dataString to access incoming JSON payloads, request.pathParams for URL parameters, and request.queryParams for query string values. Implement proper error handling and return appropriate HTTP status codes using response.setStatus() and structured JSON responses using response.setBody().
(function process(request, response) {
try {
var requestBody = JSON.parse(request.body.dataString);
var gr = new GlideRecord('incident');
gr.short_description = requestBody.title;
gr.description = requestBody.description;
gr.caller_id = requestBody.user_id;
var sysId = gr.insert();
response.setStatus(201);
response.setBody({success: true, sys_id: sysId, number: gr.number});
} catch (ex) {
response.setStatus(400);
response.setBody({success: false, error: ex.getMessage()});
}
})(request, response);Implement error handling and retry logic for reliability
Enhance your REST integrations with robust error handling by checking HTTP status codes and implementing exponential backoff retry logic for transient failures. Configure retry policies in your REST Message records by setting the Maximum Retries field and Retry Interval to handle network timeouts and temporary API unavailability. Implement custom retry logic in your scripts for specific error conditions, such as rate limiting (HTTP 429) or server errors (HTTP 5xx), using setTimeoutMs() to adjust request timeouts based on API performance characteristics. Create error logging mechanisms that capture both successful and failed API calls with sufficient detail for troubleshooting, including request payloads, response codes, and timestamps. Use ServiceNow's Event Management to create events for critical integration failures that require immediate attention from operations teams.
function callAPIWithRetry(restMessage, maxRetries) {
for (var attempt = 1; attempt <= maxRetries; attempt++) {
try {
var response = restMessage.execute();
var statusCode = response.getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
return response;
} else if (statusCode == 429 || statusCode >= 500) {
if (attempt < maxRetries) {
gs.sleep(Math.pow(2, attempt) * 1000); // Exponential backoff
continue;
}
}
throw new Error('API call failed with status: ' + statusCode);
} catch (ex) {
if (attempt == maxRetries) throw ex;
gs.sleep(Math.pow(2, attempt) * 1000);
}
}
}Configure filtering and pagination for large data sets
Implement efficient data retrieval patterns by configuring query parameters for filtering and pagination in your REST API calls to avoid timeouts and memory issues with large datasets. Use ServiceNow's encoded query syntax or custom filtering parameters supported by your target API to retrieve only relevant records, setting up dynamic filter construction based on last sync timestamps or specific field criteria. Configure pagination by implementing offset/limit or cursor-based pagination patterns depending on what your target API supports, typically using query parameters like 'offset', 'limit', 'page', or 'cursor' in your REST Message endpoint URLs. Create iterative processing logic that handles paginated responses by checking for pagination metadata in API responses and making subsequent calls until all data is retrieved. Store pagination state and filtering criteria in custom tables or system properties to support incremental synchronization and resume processing after interruptions.
function syncPaginatedData(lastSyncTime) {
var page = 1;
var hasMoreData = true;
while (hasMoreData) {
var rm = new RESTMessageV2('External System Integration', 'GET Records');
rm.setStringParameterNoEscape('page', page.toString());
rm.setStringParameterNoEscape('limit', '100');
rm.setStringParameterNoEscape('modified_since', lastSyncTime);
var response = rm.execute();
var data = JSON.parse(response.getBody());
// Process records
data.records.forEach(function(record) {
// Update ServiceNow records
});
hasMoreData = data.has_more;
page++;
}
}Test integration and monitor performance metrics
Thoroughly test your REST API integration using ServiceNow's built-in testing tools and create comprehensive test scenarios covering success cases, error conditions, and edge cases like network timeouts or malformed responses. Navigate to System Logs > REST Messages to monitor outbound API call performance, response times, and error rates, setting up alerts for integration failures or performance degradation. Use the REST API Explorer (System Web Services > REST API Explorer) to test your inbound Scripted REST APIs with various payloads and verify proper error handling and response formatting. Create automated monitoring by implementing custom metrics collection in your integration scripts, tracking API call volumes, success rates, and average response times in custom tables or ServiceNow's Performance Analytics. Set up periodic health checks using Scheduled Jobs that validate API connectivity and data synchronization accuracy, creating incidents or events when integration health checks fail.
// Health check scheduled job
var healthCheck = new RESTMessageV2('External System Integration', 'GET Health');
try {
var response = healthCheck.execute();
var statusCode = response.getStatusCode();
var responseTime = response.getResponseTime();
// Log metrics
var gr = new GlideRecord('u_integration_metrics');
gr.integration_name = 'External System';
gr.status_code = statusCode;
gr.response_time = responseTime;
gr.timestamp = new GlideDateTime();
gr.insert();
if (statusCode != 200 || responseTime > 5000) {
gs.eventQueue('integration.health.failure', null, 'External System', 'Status: ' + statusCode + ', Time: ' + responseTime);
}
} catch (ex) {
gs.eventQueue('integration.health.error', null, 'External System', ex.getMessage());
}Common Use Cases
Real-time incident synchronization with external monitoring tools
ServiceNow receives webhook notifications from monitoring tools like Datadog, New Relic, or Prometheus when system alerts are triggered, automatically creating incident records with enriched context data. The integration maps alert severity levels to ServiceNow priority fields, assigns incidents to appropriate assignment groups based on affected systems, and updates incident status when alerts are resolved. This bi-directional sync ensures that incident resolution in ServiceNow can trigger alert acknowledgment in the monitoring system, maintaining consistency across platforms. The business value includes reduced mean time to detection (MTTD), automated incident creation during off-hours, and elimination of manual ticket creation for known system alerts.
Employee onboarding automation with HR systems
ServiceNow integrates with HR systems like Workday, SuccessFactors, or BambooHR to automatically trigger IT onboarding workflows when new employees are hired or existing employees change roles. The integration retrieves employee data including department, manager, location, and job role to automatically determine required hardware, software licenses, and system access permissions. Outbound REST calls update the HR system with IT onboarding progress, equipment assignment status, and account provisioning completion timestamps. This automation reduces manual data entry errors, ensures consistent onboarding experiences, accelerates time-to-productivity for new hires, and provides audit trails for compliance requirements.
Configuration Management Database (CMDB) synchronization
ServiceNow maintains accurate CMDB data by integrating with discovery tools, cloud platforms like AWS/Azure, and asset management systems through REST APIs to automatically update configuration items (CIs) and their relationships. The integration handles incremental updates by comparing timestamps, managing CI lifecycle states, and reconciling conflicts when the same asset appears in multiple data sources. Outbound calls can trigger automated actions in connected systems when CI attributes change, such as updating monitoring configurations when server specifications are modified. The business value includes improved change impact analysis accuracy, automated compliance reporting, reduced manual CMDB maintenance overhead, and better service mapping for business applications.
Service catalog integration with provisioning systems
ServiceNow Service Catalog integrates with cloud platforms, virtualization systems, and software licensing platforms to automate resource provisioning when catalog items are requested and approved. The integration translates ServiceNow catalog variables into API calls that create virtual machines, provision cloud resources, assign software licenses, or configure network access based on the requested service specifications. Status updates from provisioning systems automatically advance ServiceNow request fulfillment tasks, and resource identifiers are captured in ServiceNow for ongoing lifecycle management. This integration delivers self-service capabilities to end users, reduces IT workload for routine provisioning tasks, ensures consistent resource configurations, and provides cost tracking for chargeback purposes.
Security incident enrichment with threat intelligence feeds
ServiceNow Security Incident Response integrates with threat intelligence platforms, SIEM systems, and vulnerability scanners to automatically enrich security incidents with contextual threat data and risk scores. The integration queries external threat feeds using indicators of compromise (IoCs) found in security incidents, retrieves vulnerability details from scanning platforms, and correlates incidents with similar attack patterns from threat intelligence databases. Bidirectional synchronization ensures that incident response actions and threat hunting findings in ServiceNow are shared back to security tools for improved detection rules and automated response orchestration. This provides security analysts with comprehensive threat context, accelerates incident triage and response decisions, improves threat hunting effectiveness, and enables proactive security posture improvements.
Troubleshooting
HTTP 401 Unauthorized errors on outbound REST calls
First, verify that your Connection and Credential records are properly configured by navigating to the credential record and testing the authentication. Check the System Logs > REST Messages to see the exact request headers being sent and compare them with the target API's authentication requirements. Common issues include expired OAuth tokens (refresh the credential), incorrect API key header names, or credential test connection failures due to network connectivity. If using OAuth 2.0, ensure the token endpoint URL, client credentials, and scope parameters exactly match the external system's requirements, and check that the ServiceNow instance can reach the OAuth server endpoint.
Request timeout errors or slow API response times
Navigate to your REST Message record and increase the Timeout value from the default 30 seconds to 60-120 seconds for APIs known to have slower response times. Monitor the System Logs > REST Messages to identify patterns in slow requests and check if specific endpoints or payload sizes correlate with timeouts. Consider implementing asynchronous processing patterns using Business Rules with async execution or Scheduled Jobs for time-intensive operations that don't require real-time responses. If the issue persists, work with the external system administrators to identify API performance bottlenecks or implement request batching to reduce the number of individual API calls.
Inbound webhook data not creating ServiceNow records
Check the System Logs > Application Logs for JavaScript errors in your Scripted REST API resource functions, looking specifically for JSON parsing errors or GlideRecord operation failures. Verify that your Scripted REST API security settings allow the external system to authenticate properly, and test the endpoint manually using REST API Explorer with sample payloads to isolate the issue. Examine the request.body.dataString content in your script to ensure the incoming data format matches your parsing logic, and add logging statements to track data flow through your processing function. Common issues include missing required fields for record creation, invalid reference field values, or access control restrictions preventing record insertion by the API user context.
Rate limiting errors (HTTP 429) from external APIs
Implement exponential backoff retry logic in your REST calls and monitor the Retry-After header values returned by rate-limited APIs to determine appropriate wait times. Review your integration frequency and batch processing logic to reduce API call volume, such as combining multiple record updates into single API calls or implementing caching for frequently requested but slowly changing data. Configure your REST Message Maximum Retries and Retry Interval settings to handle temporary rate limiting automatically, and consider implementing queuing mechanisms using ServiceNow's Event system to throttle outbound requests during peak usage periods. Work with external API administrators to understand rate limiting policies and request increased quotas if your integration requirements exceed standard limits.
JSON parsing errors in REST API responses
Add comprehensive error handling around JSON.parse() operations using try-catch blocks and log both the raw response body and parsing errors to identify malformed JSON or unexpected response formats. Check the Content-Type headers in API responses to ensure they match expected JSON format, and verify that your REST Message Accept headers are configured to request JSON responses from APIs that support multiple formats. Use response.getStatusCode() to check for successful HTTP status codes before attempting JSON parsing, as error responses may return HTML error pages or plain text messages instead of JSON. Consider implementing response validation logic that checks for required fields and data types before processing parsed JSON data to prevent downstream errors in ServiceNow record operations.
SSL certificate verification failures for HTTPS endpoints
Navigate to System Properties > SSL and verify that your ServiceNow instance has the necessary certificate authority (CA) certificates installed to validate the target API's SSL certificate chain. For internal or self-signed certificates, you may need to import the certificate into ServiceNow's trust store through System Certificates. Check the System Logs > REST Messages for specific SSL error details, and work with your network security team to ensure certificate validity and proper certificate chain configuration. As a temporary troubleshooting step, you can disable SSL verification in REST Message records, but this should only be used in development environments and never in production due to security risks.
Pro Tips
- →Implement correlation IDs in all REST API calls by adding custom headers like X-Correlation-ID with unique values (sys_id or generated GUIDs) to enable end-to-end request tracing across ServiceNow and external systems. This dramatically improves troubleshooting capabilities when issues span multiple systems and allows you to correlate ServiceNow logs with external system logs for comprehensive debugging.
- →Use ServiceNow's Transform Maps with REST integrations by creating Import Set tables that match your API response structure, then leverage the robust Transform Map functionality for complex data transformations, field mappings, and coalescing logic. This approach separates data extraction from data transformation, making your integrations more maintainable and allowing business users to modify field mappings without code changes.
- →Leverage ServiceNow's Event system for asynchronous REST API processing by triggering events from synchronous operations (like Business Rules) and handling the actual API calls in separate Script Actions. This pattern prevents user interface delays, allows for retry logic and error handling without affecting user experience, and enables batch processing of multiple API calls for better performance and rate limit management.
- →Implement circuit breaker patterns in high-volume REST integrations by tracking API failure rates and temporarily disabling API calls when error thresholds are exceeded. Store circuit breaker state in System Properties or custom tables, automatically re-enable after cool-down periods, and use this pattern to prevent cascading failures when external systems experience outages.
- →Create reusable Script Includes for common REST operations like authentication token management, response parsing, and error handling to maintain consistency across multiple integrations. Implement utility functions for common patterns like pagination handling, rate limit detection, and response caching to reduce code duplication and improve maintainability across your REST integration portfolio.
- →Monitor REST integration performance using ServiceNow's Performance Analytics by creating custom metrics that track API response times, success rates, and throughput volumes over time. Set up automated alerting based on performance degradation trends and use these metrics to optimize integration timing, identify capacity planning needs, and demonstrate integration reliability to business stakeholders.
Known Limitations
- —ServiceNow imposes a default limit of 100 concurrent outbound HTTP requests per instance, which can create bottlenecks for high-volume integrations or when multiple integrations compete for connection resources. This limit affects batch processing scenarios and may require implementing queuing mechanisms or request throttling to prevent connection pool exhaustion during peak usage periods.
- —REST Message timeout values have a maximum configuration limit of 300 seconds (5 minutes), which may be insufficient for extremely long-running API operations like large data exports or complex analytical queries. For operations requiring longer processing times, you must implement asynchronous patterns with status polling or use webhook callbacks for completion notification.
- —ServiceNow's JavaScript engine does not support modern ES6+ features in server-side scripts, limiting developers to ES5 syntax and requiring workarounds for advanced JavaScript patterns like async/await, arrow functions, or destructuring. This can make complex JSON manipulation and promise-based API patterns more verbose and harder to maintain compared to modern JavaScript environments.
- —Scripted REST APIs in ServiceNow have limited built-in support for advanced HTTP features like file uploads with multipart/form-data, WebSocket connections, or streaming responses, requiring custom implementations or alternative approaches for these use cases. Large file handling through REST APIs may also encounter memory limitations during processing.
- —ServiceNow's Connection and Credential system does not support some advanced authentication flows like PKCE (Proof Key for Code Exchange) for OAuth 2.0 or mutual TLS authentication, potentially requiring custom authentication implementations using Script Includes or MID Server capabilities. Complex authentication scenarios may need workarounds that reduce the security benefits of the built-in credential management system.
Frequently Asked Questions
Should I use Integration Hub ETL spokes or native REST Message records for my REST API integration?
Use Integration Hub ETL spokes when you need visual workflow design, built-in error handling, and step-by-step execution tracking, especially for complex multi-step integrations involving data transformations. Choose native REST Message records for simple integrations, custom authentication requirements, or when you need fine-grained control over request/response handling in server-side scripts. Integration Hub provides better monitoring and maintenance capabilities but requires additional licensing, while REST Messages offer more flexibility and are included in the base platform. Consider your team's technical expertise, licensing constraints, and long-term maintenance requirements when making this decision.
How do I handle OAuth 2.0 token refresh automatically in ServiceNow REST integrations?
ServiceNow's OAuth 2.0 credentials automatically handle token refresh when properly configured with valid refresh_token, token endpoint URL, and client credentials in the Connection record. The platform automatically detects HTTP 401 responses and attempts token refresh before retrying the original request. Ensure your OAuth credential includes the refresh_token scope and that the external system supports refresh tokens with sufficient expiration times. If automatic refresh fails consistently, check the System Logs for OAuth-specific errors and verify that your client credentials have the necessary permissions to request new tokens from the authorization server.
What's the best practice for handling large JSON responses that exceed ServiceNow's memory limits?
Implement streaming or pagination patterns by requesting smaller data chunks using API pagination parameters like limit/offset or cursor-based pagination to avoid memory exhaustion. Process each paginated response immediately and store results in ServiceNow tables rather than accumulating large JSON objects in memory. Use server-side chunking by implementing Scheduled Jobs that process data in batches with controlled intervals between API calls. For extremely large datasets, consider using MID Server capabilities with file-based processing or implementing asynchronous processing patterns where the external system breaks large responses into multiple webhook calls to ServiceNow.
How can I secure REST API credentials and prevent them from being exposed in logs or scripts?
Always store sensitive credentials in Connection & Credential records rather than hardcoding them in scripts, as ServiceNow encrypts these values and masks them in system logs. Use the minimal necessary permissions principle by creating dedicated API users in external systems with restricted access scopes for ServiceNow integration purposes. Implement credential rotation policies by regularly updating API keys and OAuth credentials, and monitor credential usage through Connection record audit logs. Avoid logging credential values or sensitive request/response data in custom gs.log() statements, and use ServiceNow's built-in REST Message logging which automatically masks authentication headers and sensitive data fields.
Can I use ServiceNow REST APIs to integrate with on-premises systems behind corporate firewalls?
Yes, but you'll need to install and configure a MID Server within your corporate network to act as a proxy between ServiceNow cloud and on-premises systems. The MID Server establishes outbound HTTPS connections to ServiceNow and can reach internal systems, enabling REST API calls to internal endpoints without requiring inbound firewall rules. Configure your REST Message records to use MID Server selection by setting the MID Server field or using MID Server clusters for high availability. Ensure your MID Server has network access to target internal APIs and consider implementing additional security measures like certificate-based authentication or IP allowlisting for sensitive internal systems accessed through MID Server proxy.
How do I implement proper error handling and retry logic for unreliable external APIs?
Implement a comprehensive error handling strategy that distinguishes between transient errors (network timeouts, HTTP 5xx) that warrant retries and permanent errors (HTTP 4xx client errors) that should not be retried. Use exponential backoff algorithms with jitter to avoid overwhelming recovering systems, and configure maximum retry limits to prevent infinite loops. Capture detailed error context including request payloads, response codes, and timestamps in custom tables or System Logs for troubleshooting. Implement circuit breaker patterns for high-volume integrations to temporarily disable API calls when failure rates exceed thresholds, and use ServiceNow's Event system to notify administrators of integration failures that require manual intervention.
What are the performance implications of synchronous vs asynchronous REST API calls in ServiceNow?
Synchronous REST API calls in Business Rules or UI actions can cause significant user experience delays, especially for slow external APIs, and may trigger timeout errors if calls exceed 30 seconds in interactive contexts. Asynchronous processing using async Business Rules, Scheduled Jobs, or Event-driven Script Actions provides better user experience but introduces complexity in error handling and status tracking. Consider hybrid approaches where immediate validation or critical data is processed synchronously, while non-critical operations are handled asynchronously. Monitor the System Logs > REST Messages to track API performance and adjust your synchronous/asynchronous patterns based on actual response times and user impact. Use asynchronous patterns for batch operations, non-critical notifications, or any integration that doesn't require immediate feedback to the user interface.
Test Your Knowledge
Quick 3-question quiz — see how your ServiceNow skills stack up.
A list view on a table with millions of records is slow. Best fix?
Select an answer to continue