Scripted REST APIs
Scripted REST APIs in ServiceNow provide a powerful framework that allows developers to create custom RESTful web services directly within the platform. Unlike the standard REST API that exposes existing tables and records, Scripted REST APIs give developers full control over the request handling, … Scripted REST APIs in ServiceNow provide a powerful framework that allows developers to create custom RESTful web services directly within the platform. Unlike the standard REST API that exposes existing tables and records, Scripted REST APIs give developers full control over the request handling, response formatting, and business logic execution. A Scripted REST API consists of three main components: the API definition, API resources, and the scripted logic. The API definition establishes the base path and namespace for your custom endpoint. Resources define the specific HTTP methods (GET, POST, PUT, PATCH, DELETE) and relative paths that clients can call. The scripted logic, written in server-side JavaScript, processes incoming requests and constructs appropriate responses. When creating a Scripted REST API, developers navigate to System Web Services > Scripted REST APIs and define the API name, API ID, and namespace. Resources are then added under the API, where each resource specifies the HTTP method, relative path (which can include path parameters like /{id}), and the server-side script that handles the request. Within the resource script, developers have access to the request object (containing headers, query parameters, path parameters, and request body) and the response object (used to set status codes, headers, and the response body). This allows for sophisticated data transformation, validation, authentication checks, and integration with external systems. Key benefits include the ability to create versioned APIs, implement custom authentication and authorization, format responses in any structure (not limited to ServiceNow's default table API format), aggregate data from multiple sources, and enforce business rules before returning data. Scripted REST APIs also support content negotiation, allowing developers to return data in JSON, XML, or other formats based on the Accept header. They integrate seamlessly with ServiceNow's access control mechanisms and can leverage existing Script Includes and GlideRecord queries. This capability is essential for the Certified Application Developer exam, as it demonstrates proficiency in building custom integrations and exposing ServiceNow functionality to external consumers in a controlled, secure manner.
Scripted REST APIs in ServiceNow – Complete Guide for CAD Exam
Introduction
Scripted REST APIs are a powerful feature in ServiceNow that allow developers to create custom RESTful web service endpoints. Unlike the standard Table API or other out-of-box APIs, Scripted REST APIs give you full control over the request handling, response format, HTTP methods, and business logic. For the ServiceNow Certified Application Developer (CAD) exam, understanding Scripted REST APIs is essential as they fall under the Working with External Data domain.
Why Are Scripted REST APIs Important?
Scripted REST APIs are important for several key reasons:
1. Custom Integration Endpoints: Organizations often need to expose specific data or functionality to external systems in a tailored format. Scripted REST APIs allow you to define exactly what data is exposed and how it is structured, rather than relying on generic table-level access.
2. Security and Control: Instead of granting broad access to entire tables via the Table API, Scripted REST APIs let you create narrow, purpose-built endpoints that expose only the data and operations you intend, reducing your attack surface.
3. Custom Business Logic: You can embed complex business logic, data transformations, validations, and multi-table operations within a single API call, simplifying the integration for consuming applications.
4. Versioning: Scripted REST APIs support API versioning, allowing you to evolve your APIs over time without breaking existing integrations.
5. Flexible Response Formats: You can return data in JSON, XML, text, or any custom format required by the consuming application.
What Is a Scripted REST API?
A Scripted REST API is a ServiceNow feature (found under System Web Services > Scripted REST APIs) that lets developers define custom API endpoints with the following components:
- API Definition (Scripted REST API record): This is the parent record that defines the API namespace, API ID, and base path. It acts as a container for one or more resources. The base URL pattern is: https://instance.service-now.com/api/{namespace}/{api_id}
- API Resources: These are child records under the API definition. Each resource defines a specific endpoint path (relative path), the HTTP method it responds to (GET, POST, PUT, PATCH, DELETE), and the server-side script that handles the request. A single Scripted REST API can have multiple resources.
- Namespace: By default, custom Scripted REST APIs use your company's namespace or a custom application scope namespace. This helps prevent naming conflicts.
- API Version: You can optionally version your API (e.g., v1, v2) to manage changes over time.
How Does It Work?
Here is the step-by-step process of how Scripted REST APIs work:
Step 1: Create the Scripted REST API Record
Navigate to System Web Services > Scripted REST APIs and create a new record. Provide a name and API ID. The API ID becomes part of the URL path.
Step 2: Create API Resources
Under the Scripted REST API record, create one or more resources. For each resource, you define:
- HTTP Method: GET, POST, PUT, PATCH, or DELETE
- Relative Path: The path segment appended to the base URL. You can include path parameters using curly braces, e.g., /{incident_id}
- Script: The server-side JavaScript that processes the request and generates the response
Step 3: Write the Resource Script
Inside the script, you have access to several important objects:
- request (RESTAPIRequest): Provides access to request headers, query parameters, path parameters, and the request body.
- request.pathParams – Access path parameters defined in the relative path
- request.queryParams – Access query string parameters
- request.body.dataString – Access the raw request body as a string
- request.body.data – Access the parsed request body as an object
- request.getHeader('header_name') – Access specific request headers
- response (RESTAPIResponse): Allows you to set the HTTP status code, response headers, and response body.
- response.setStatus(200) – Set the HTTP response status code
- response.setHeader('header_name', 'value') – Set a response header
- response.setBody(object) – Set the response body (typically a JavaScript object that gets serialized to JSON)
- RESTAPIResponseStream: For streaming large responses, you can use response.getStreamWriter() to write data incrementally.
Step 4: Access Control
You can control who has access to your Scripted REST API by:
- Requiring authentication (basic auth, OAuth, mutual auth)
- Specifying ACLs
- Checking roles within the script itself
- Setting the Requires authentication checkbox on the API definition
- Using the Allowed roles field on the resource to restrict access to specific roles
Step 5: Testing
You can test Scripted REST APIs using tools like Postman, curl, or the ServiceNow REST API Explorer (System Web Services > REST API Explorer). The REST API Explorer allows you to discover and test both out-of-box and custom APIs.
Example Scenario
Suppose you want to create an API endpoint that returns active incidents for a given assignment group:
- API ID: incident_api
- Resource HTTP Method: GET
- Relative Path: /active/{group_name}
- Script:
(function process(request, response) {
var groupName = request.pathParams.group_name;
var gr = new GlideRecord('incident');
gr.addQuery('active', true);
gr.addQuery('assignment_group.name', groupName);
gr.query();
var incidents = [];
while (gr.next()) {
incidents.push({
number: gr.getValue('number'),
short_description: gr.getValue('short_description'),
state: gr.getValue('state')
});
}
response.setStatus(200);
response.setBody({result: incidents});
})(request, response);
The endpoint URL would be: https://instance.service-now.com/api/{namespace}/incident_api/active/Network
Key Concepts to Remember
- Scripted REST APIs run in the global scope or within a scoped application. When created in a scoped app, the namespace is automatically the application's scope name.
- The Content-Type header of the response defaults to application/json but can be changed.
- Path parameters are defined using curly braces {} in the relative path and accessed via request.pathParams.
- Query parameters are accessed via request.queryParams, which returns an array of values for each parameter name.
- You can define multiple resources (endpoints) under a single Scripted REST API, each with different HTTP methods and paths.
- Scripted REST APIs support content negotiation — you can check the Accept header to determine the desired response format.
- The request body for POST/PUT/PATCH requests can be accessed as a string or parsed object.
- Scripted REST APIs are different from Scripted Web Services (SOAP-based) — make sure not to confuse them on the exam.
Scripted REST APIs vs. Other APIs
- Table API: Out-of-box, provides CRUD operations on any table. Less control over response format and logic. Scripted REST APIs provide full customization.
- Import Set API: Used specifically for importing data into staging tables. Not for general-purpose custom endpoints.
- Scripted Web Services: SOAP-based, older technology. Scripted REST APIs are RESTful and modern.
- REST Message / REST Message Steps: These are for outbound REST calls (ServiceNow calling external systems). Scripted REST APIs are inbound (external systems calling ServiceNow).
Exam Tips: Answering Questions on Scripted REST APIs
1. Know the difference between inbound and outbound: Scripted REST APIs are inbound — they define endpoints that external systems call. REST Messages are outbound — they are used when ServiceNow calls external systems. This distinction is commonly tested.
2. Understand the component hierarchy: A Scripted REST API record is the parent container. Resources are child records that define individual endpoints. Each resource has its own HTTP method, relative path, and script. Expect questions about this structure.
3. Know the key objects: The request (RESTAPIRequest) and response (RESTAPIResponse) objects are critical. Know how to access path parameters (request.pathParams), query parameters (request.queryParams), request body (request.body.data), and how to set the response (response.setBody(), response.setStatus()).
4. Path parameters syntax: Remember that path parameters are defined with curly braces in the relative path (e.g., /{sys_id}) and accessed using request.pathParams.sys_id. This is a frequent exam topic.
5. Query parameters return arrays: Be aware that request.queryParams.param_name returns an array of values, not a single value. To get a single value, you typically use index [0], e.g., request.queryParams.category[0].
6. Authentication and security: Know that Scripted REST APIs can require authentication and can restrict access by roles. The Requires authentication checkbox and Allowed roles field are key security mechanisms.
7. Namespace and URL structure: The full URL follows the pattern: https://instance.service-now.com/api/{namespace}/{api_id}/{relative_path}. For scoped applications, the namespace is the scope name. For global scope, you define the namespace yourself.
8. Versioning: Know that Scripted REST APIs support versioning and that the version can be included in the URL path.
9. HTTP methods matter: Each resource is tied to a specific HTTP method. A GET resource will not handle POST requests. If you need to support multiple methods on the same path, create multiple resources.
10. Watch for distractor answers: The exam may include options mentioning Scripted Web Services (SOAP), REST Messages (outbound), or the Table API. Make sure you select the answer that specifically relates to creating custom inbound RESTful endpoints — that is Scripted REST APIs.
11. REST API Explorer: Remember that the REST API Explorer can be used to discover and test Scripted REST APIs, in addition to out-of-box APIs.
12. Practice reading code snippets: The exam may present a script from a Scripted REST API resource and ask what it does or what the output would be. Be comfortable reading scripts that use GlideRecord queries within the API resource script and construct custom response bodies.
13. Error handling: Know that you can set custom HTTP status codes (e.g., 400 for bad request, 404 for not found, 500 for server error) using response.setStatus() and return meaningful error messages in the response body.
14. Scripted REST APIs and application scope: When created within a scoped application, the Scripted REST API is part of that application and uses the application's namespace. This is important for update sets and application deployment.
Summary
Scripted REST APIs are a fundamental tool for ServiceNow developers who need to create custom, secure, and well-structured inbound RESTful endpoints. They provide full control over request processing and response generation through server-side JavaScript. For the CAD exam, focus on understanding the architecture (API definition + resources), the request/response objects and their methods, the URL structure with namespaces and path parameters, and the distinction between inbound Scripted REST APIs and outbound REST Messages. Mastering these concepts will help you confidently answer exam questions on this topic.
🎓 Unlock Premium Access
ServiceNow Certified Application Developer + ALL Certifications
- 🎓 Access to ALL Certifications: Study for any certification on our platform with one subscription
- 3305 Superior-grade ServiceNow Certified Application Developer practice questions
- Unlimited practice tests across all certifications
- Detailed explanations for every question
- CAD: 5 full exams plus all other certification exams
- 100% Satisfaction Guaranteed: Full refund if unsatisfied
- Risk-Free: 7-day free trial with all premium features!