This scripted REST API ServiceNow example builds a small incident API from scratch: one GET resource that returns an incident by number, one POST resource that adds a comment, and the security and testing steps that make it usable. Create the API under System Web Services > Scripted Web Services > Scripted REST APIs, add a resource for each method and path, write the handler script, then call it with curl or the REST API Explorer. Each step is below with working code.
If you already know the basics and want design rules, read the companion guide on Scripted REST API best practices. This article is the hands-on version.
What we are building
Two endpoints, inside a scoped application on a development instance:
| Method | Path | Purpose |
|---|---|---|
| GET | /api/<scope>/incident_api/{number} | Return a summary of one incident |
| POST | /api/<scope>/incident_api/{number}/comment | Add a customer-visible comment |
Replace <scope> with your application scope, for example x_acme_support. The GET endpoint also accepts an optional fields query parameter so the caller can ask for a smaller response.
Step 1: Create the API record
- Open your scoped application in Studio, or set it as your current application.
- Navigate to System Web Services > Scripted Web Services > Scripted REST APIs and select New.
- Set Name to
Incident APIand API ID toincident_api. - Save.
The form now shows the Base API path, built from the namespace and the API ID. For a scoped application the namespace is the scope name, so the base path looks like /api/x_acme_support/incident_api.
The API record lives in sys_ws_definition. Each resource you add next lives in sys_ws_operation. Both are captured in your update set along with the rest of the application.
Step 2: Add the GET resource
In the Resources related list, select New and fill in:
- Name:
Get incident - HTTP method: GET
- Relative path:
/{number}
The braces define a path parameter. Whatever the caller puts in that segment arrives in request.pathParams.number.
Paste this into the Script field:
(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
var number = request.pathParams.number;
if (!/^INC\d+$/.test(number)) {
return new sn_ws_err.BadRequestError('Expected an incident number such as INC0010001');
}
// GlideRecordSecure applies the caller's ACLs to the query and fields
var inc = new GlideRecordSecure('incident');
inc.addQuery('number', number);
inc.setLimit(1);
inc.query();
if (!inc.next()) {
return new sn_ws_err.NotFoundError('No incident found with number ' + number);
}
var allowed = ['number', 'short_description', 'state', 'priority', 'assignment_group', 'assigned_to', 'sys_updated_on'];
var requested = allowed;
// Each query parameter value is an array of strings
if (request.queryParams.fields && request.queryParams.fields[0]) {
requested = request.queryParams.fields[0].split(',').filter(function (f) {
return allowed.indexOf(f.trim()) > -1;
}).map(function (f) {
return f.trim();
});
}
var body = { sys_id: inc.getUniqueValue() };
requested.forEach(function (field) {
body[field] = {
value: inc.getValue(field),
display_value: inc.getDisplayValue(field)
};
});
response.setStatus(200);
response.setBody(body);
})(request, response);
A few details worth noticing:
- Validate the path parameter first. The regular expression rejects anything that is not an incident number before a query runs.
GlideRecordSecureinstead ofGlideRecord. The API runs as the authenticated caller, andGlideRecordSecureenforces that caller's read ACLs on rows and fields. A plainGlideRecordwould return data the caller is not allowed to see.- An allowlist for
fields. The caller can narrow the response but cannot ask for fields you did not intend to expose. setBodywraps the object. ServiceNow returns your object inside aresultproperty, so the caller receives{"result": {...}}.
For larger lookups, the same query rules from the GlideRecord query performance guide apply: filter on indexed fields and limit the rows you read.
Step 3: Add the POST resource
Add a second resource:
- Name:
Add comment - HTTP method: POST
- Relative path:
/{number}/comment
Script:
(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
var number = request.pathParams.number;
var data = request.body.data; // parsed JSON body; read it once
if (!data || typeof data.comment !== 'string' || !data.comment.trim()) {
return new sn_ws_err.BadRequestError('Body must be JSON with a non-empty "comment" string');
}
if (data.comment.length > 4000) {
return new sn_ws_err.BadRequestError('Comment must be 4000 characters or fewer');
}
var inc = new GlideRecordSecure('incident');
inc.addQuery('number', number);
inc.setLimit(1);
inc.query();
if (!inc.next()) {
return new sn_ws_err.NotFoundError('No incident found with number ' + number);
}
if (!inc.canWrite()) {
var denied = new sn_ws_err.ServiceError();
denied.setStatus(403);
denied.setMessage('Not allowed to update this incident');
return denied;
}
inc.setValue('comments', data.comment.trim());
inc.update();
response.setStatus(201);
response.setBody({
number: inc.getValue('number'),
sys_id: inc.getUniqueValue(),
message: 'Comment added'
});
})(request, response);
request.body.data gives you the parsed JSON. Read it once into a variable. The body is a stream that can only be consumed once, so if you read data and then dataString, the second read comes back empty. Pick one: data for parsed JSON, dataString for the raw text.
The sn_ws_err objects are the cleanest way to return errors. BadRequestError returns 400, NotFoundError returns 404, and ServiceError lets you set any status code with setStatus, plus setMessage and setDetail. ServiceNow formats the error body for you, so every failure has the same shape. If you prefer a shared helper for success and error envelopes, the REST API response helper script include shows one approach.
Step 4: Secure the resources
Open each resource and check the Security section:
- Requires authentication should stay selected. Without it, anyone who can reach the instance can call the endpoint.
- Requires ACL authorization should stay selected. New resources use the Scripted REST External Default ACL, which stops users with the
snc_externalrole from calling the API. Open that ACL on your instance to see exactly what it checks.
For a real integration, create a dedicated integration user with only the roles it needs, and add an ACL of type REST_Endpoint for this API that requires a role you assign to that user. Then the endpoint ACL decides who can call the API at all, and GlideRecordSecure decides which incident data the caller can read or change. If a call fails with 403 and you cannot see why, the ACL troubleshooting guide walks through finding the rule that blocked it.
Step 5: Test it
The fastest first test is the REST API Explorer (System Web Services > REST > REST API Explorer). Choose your namespace and Incident API, pick a resource, fill in the path parameter, and send. The Explorer also generates sample code for curl and other clients.
From a terminal, use a test user on your development instance:
# GET with a field filter
curl -s -u 'api.test.user:password' \
-H 'Accept: application/json' \
'https://<instance>.service-now.com/api/x_acme_support/incident_api/INC0010001?fields=number,state,priority'
# POST a comment
curl -s -u 'api.test.user:password' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-X POST \
-d '{"comment": "Customer confirmed the fix on their laptop."}' \
'https://<instance>.service-now.com/api/x_acme_support/incident_api/INC0010001/comment'
A successful GET returns something like:
{
"result": {
"sys_id": "...",
"number": { "value": "INC0010001", "display_value": "INC0010001" },
"state": { "value": "2", "display_value": "In Progress" },
"priority": { "value": "3", "display_value": "3 - Moderate" }
}
}
Then test the failures on purpose:
| Test | Expected status |
|---|---|
Path /abc | 400 |
Path /INC9999999 that does not exist | 404 |
POST with {} as the body | 400 |
| Wrong password | 401 |
| User without the endpoint role | 403 |
| User who can read but not write the incident, on POST | 403 |
If a test returns 500, check the system log for the script error. Wrap risky parts of the handler in try/catch, log the detail with gs.error, and return a generic ServiceError so callers never see stack traces.
Step 6: Version it before anyone depends on it
On the API record, use Enable versioning before the first consumer goes live. Versioned resources are served at /api/<scope>/incident_api/v1/..., and you can add a v2 later without breaking existing callers. Retrofitting versions after consumers hard-code the unversioned path is much harder.
Checklist before you hand it over
- API created in the right scope, captured in an update set
- Path and query parameters validated before any query
- Query parameter values read as arrays (
[0]) GlideRecordSecureor explicitcanReadandcanWritechecks- Field allowlist on anything the caller can choose
- Errors returned with
sn_ws_errobjects, never raw stack traces - Requires authentication and Requires ACL authorization selected
- A dedicated integration user and a REST_Endpoint ACL
- Every failure case tested, not just the happy path
- Versioning enabled before the first consumer
When ServiceNow needs to call another system rather than be called, the patterns are different. The outbound REST integration guide and the REST API client script cover that direction.