← All guides

Scripted REST API ServiceNow Example: Build One End to End

A worked Scripted REST API example in ServiceNow: create the API, add GET and POST resources, read parameters, return errors, secure it, and test with curl.

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:

MethodPathPurpose
GET/api/<scope>/incident_api/{number}Return a summary of one incident
POST/api/<scope>/incident_api/{number}/commentAdd 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

  1. Open your scoped application in Studio, or set it as your current application.
  2. Navigate to System Web Services > Scripted Web Services > Scripted REST APIs and select New.
  3. Set Name to Incident API and API ID to incident_api.
  4. 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.
  • GlideRecordSecure instead of GlideRecord. The API runs as the authenticated caller, and GlideRecordSecure enforces that caller's read ACLs on rows and fields. A plain GlideRecord would 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.
  • setBody wraps the object. ServiceNow returns your object inside a result property, 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_external role 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:

TestExpected status
Path /abc400
Path /INC9999999 that does not exist404
POST with {} as the body400
Wrong password401
User without the endpoint role403
User who can read but not write the incident, on POST403

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])
  • GlideRecordSecure or explicit canRead and canWrite checks
  • Field allowlist on anything the caller can choose
  • Errors returned with sn_ws_err objects, 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.

Frequently asked questions

Where do I create a Scripted REST API in ServiceNow?

Navigate to System Web Services > Scripted Web Services > Scripted REST APIs and select New. The API record is stored in the sys_ws_definition table, and each resource you add to it is stored in sys_ws_operation.

What is the URL of a Scripted REST API?

The base path is /api/<namespace>/<api_id>. For a scoped application the namespace is the scope name. Each resource adds its relative path to the base path, so a resource with the path /{number} becomes /api/<namespace>/<api_id>/{number}.

Why does request.queryParams.limit return an array?

Each value in request.queryParams is an array of strings, because a query parameter can appear more than once in a URL. Read the first element, for example request.queryParams.limit[0], and convert it to a number yourself.

How do I return a 404 or 400 from a Scripted REST API?

Return one of the error objects in the sn_ws_err namespace, such as new sn_ws_err.NotFoundError('message') or new sn_ws_err.BadRequestError('message'). ServiceNow sets the status code and writes a standard error body. For other codes, use sn_ws_err.ServiceError and call setStatus, setMessage and setDetail.

More practical ServiceNow notes.

Back to the guides