---
sourceDocument: Brazil API Reference
sourceDocumentLink: https://www.servicenow.com/docs/r/api-reference

 Release :

    - brazil

ft:locale :

    - en-US

ft:publication_title :

    - Brazil API Reference

ft:clusterId :

    - crapiref

bundleId :

    - crapiref

workflow :

    - Creator


---

# Scripted REST API example - script samples

# Scripted REST API example - script samples {#ariaid-title1}

Release version: Brazil  
Updated September 10, 2026  
![](https://www.servicenow.com/docs/portal-asset/ico-clock) 4 minutes to read
Summarize  
![AI sparkle icon](https://servicenow.com/docs/portal-asset/ai-sparkle-icon) Summarized using AI  
This content was generated using new OpenAI-powered functionality. Results are provided on an as is basis and are not guaranteed to be accurate or complete.  

## Summary of Scripted REST API example - script samples

This document provides practical script examples for creating and handling scripted REST API resources in ServiceNow.
It covers common use cases such as retrieving query and path parameters, processing POST requests with various body types, utilizing script includes for reusable code, and managing error responses.
Additionally, it demonstrates proper function syntax and highlights potential serialization errors when handling requests and responses.
Show full answer Show less  

## Key Features

* **Query Parameters (GET):** Extract query parameters and custom headers from a GET request to tailor API behavior.
* **Path Parameters (GET):** Access and return path parameters to support RESTful routing and resource identification.
* **Script Includes:** Invoke reusable server-side code from REST API scripts to improve maintainability and reduce duplication.
* **POST Requests:** Handle POST bodies both as strings and binary data, enabling flexible input processing.
* **Error Handling:** Respond with standard HTTP errors including Not Acceptable, Bad Request, Conflict, Not Found, and Unsupported Media Type. Also supports custom service errors with specific status codes and messages.
* **Function Syntax:** Emphasizes wrapping functions in parentheses to avoid syntax errors in scripted REST APIs.
* **Serialization Errors:** Warns against returning or setting request/response objects directly in responses to prevent serialization issues.
* **Data Parsing Example:** Shows how to parse and return multiple objects from a JSON or XML POST body, supporting different content types.

## Key Outcomes

ServiceNow customers can leverage these script samples to:

* Quickly implement REST API endpoints that handle various HTTP methods and input data formats.
* Improve API robustness by correctly managing errors and validating request formats.
* Reuse common logic via script includes, enhancing code clarity and maintainability.
* Ensure proper syntax and avoid common pitfalls such as serialization errors and function declaration mistakes.
* Support both JSON and XML request payloads while consistently returning JSON responses based on Accept headers.

These examples provide a practical foundation for developing effective and standards-compliant scripted REST APIs within the ServiceNow platform.  
These examples demonstrate how to create various resource scripts for a scripted REST
API.

## Query parameters GET example

This example demonstrates how to get query parameter values from a request.

    /**
     * GET - Sample Request API - Query Params
     */
    (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
        var uri = request.uri;
        var url = request.url;
        var queryParams = request.queryParams;
        var customHeader = request.getHeader('X-Custom');

        return {
            "uri": uri,
            "url": url,
            "queryParams": queryParams,
            "customHeader": customHeader
        };

    })(request, response);

## Path parameters GET example

This example demonstrates how to get path parameter values from a request.

    /**
     * GET - Sample Request API - Path Params
     */
    (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
        var uri = request.uri;
        var url = request.url;
        var path = request.pathParams;

        return {
            "uri": uri,
            "url": url,
            "path_params": path,
            "path.id": path.id
        };
    })(request, response);

## Script include GET example

This example demonstrates how to use a script include to provide a response. By using a
script include you can reuse common code and maintain readability in the REST service
scripts.

    /**
     * GET - Sample Request API - Script Include
     */
    (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
        var responseObj = global.SampleDataUtil.getSampleJSON();
        return responseObj;
    })(request, response);

## String POST example

This example demonstrates how to parse a POST message with a string body and send a
response based on the request.

    /**
     *  POST - Sample Request API - dataString
     *  sample usage:
     *  var requestBody = request.body;
     *  var requestString = requestBody.dataString;
     */
    (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
        var requestBody = request.body;
        var requestString = requestBody.dataString;
        return {"requestString": requestString};
    })(request, response);

## Binary POST example

This example demonstrates how to parse a POST message with a binary body and send a
response based on the request.

    /**
     * POST - Sample Request API - Body
     */
    (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
        var body = request.body.data;
        //do any additional processing on the request body, such as inserting a new record.
        return {
            "body.id": body.id
        };
    })(request, response);

## Not acceptable error example

This example demonstrates how to respond with a not acceptable error. Use this error type
when the request Accept header value is not supported by the web service.

    /**
     * Sample Not Acceptable Error Sample
     */
    (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
        response.setError(new sn_ws_err.NotAcceptableError('sample error message'));
    })(request, response);

## Bad request error example

This example demonstrates how to respond with a bad request error. Use this error type to
indicate a mistake in the request syntax.

    /**
     * Bad Request Error Sample
     */
    (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
        response.setError(new sn_ws_err.BadRequestError('sample error message'));
    })(request, response);

## Conflict error example

This example demonstrates how to respond with a conflict error. Use this error type in the
event of multiple conflicting requests, such as multiple updates to the same record.

    /**
     * Error Response: Conflict Error Sample
     */
    (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
        response.setError(new sn_ws_err.ConflictError('sample error message'));
    })(request, response);

## Not found error example

This example demonstrates how to respond with a not found error. Use this error type if the
requested resource does not exist or is unavailable.

    /**
     * Error Response: Not Found Error Sample
     */
    (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
        response.setError(new sn_ws_err.NotFoundError('sample error message'));
    })(request, response);

## Unsupported media type error example

This example demonstrates how to respond with an unsupported media type error. Use this
error type to indicate that the Content-Type of the request is unsupported.

    /**
     * Error Response: Unsupported Media Type Error Sample
     */
    (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
        response.setError(new sn_ws_err.UnsupportedMediaTypeError('sample error message'));
    })(request, response);

## Service error example

This example demonstrates how to respond with a generic service error. The ServiceError
object allows you to define the status code, message, and error detail. Use a ServiceError
if the predefined error types do not meet your needs.

    /**
     * Error Response: Custom Error Sample
     */
    (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
        var myError = new sn_ws_err.ServiceError();
        myError.setStatus(418);
        myError.setMessage("I am a Teapot");
        myError.setDetail("Here are the details about this error");
        response.setError(myError);
    })(request, response);

## Function parentheses error example {#r_ScriptedRESTServiceScriptExamples__section_lwv_nzk_f2c}

This example demonstrates that if a function is not wrapped in parentheses, it results in a error. Include parentheses with all functions.

    (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
    	gs.info("message: {0}", request.body.data.message);
    })(request, response);

    function test() {
    	gs.info("test");
    }(request, response);

## Serialization error example {#r_ScriptedRESTServiceScriptExamples__section_c35_21l_f2c}

This example demonstrates that if the request is set as a body to the response, it can result in a serialization error.

    setBody_request:
        response.setBody(request);

This example demonstrates that if the response is set as a body to the response, it can result in a serialization error.

    setBody_response:
        response.setBody(response);

This example demonstrates that if the request is returned, it can result in a serialization error.

    return_request:
        return request;

This example demonstrates that if the response is returned, it can result in a serialization error.

    return_response:
        return response;

## Scripted REST resource script example

This sample REST API resource script parses the name and id values from the request body and returns those values in the response.

    /**
     * POST - Sample Request API - Body
     */
    (function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
    var body = request.body.data,
    id0,name0,id1,name1;
    name0 = body[0].name; // 'user0'
    id0 = body[0].id; // '1234'
    name1 = body[1].name; // 'user1'
    id1 = body[1].id; // '5678'

    return {
    "id": id0,
    "name": name0,
    "id1": id1,
    "name1": name1
    };
    })(request, response);

## Requests

The API can accept both XML and JSON requests.{#r_ScriptedRESTServiceScriptExamples__table_xkb_2vq_xs__entry__2}

| JSON Request | XML Request |
|-|-|
| POST /api/sn_demo_api/v1/example/body HTTP/1.1 Content-Type: application/json Accept: application/json Host: <instance>.service-now.com Connection: close Content-Length: 91 [ { "name": "user0", "id": 1234 }, { "name": "user1", "id": 5678 } ] | POST /api/sn_demo_api/v1/example/body HTTP/1.1 Content-Type: application/xml Accept: application/json Host: <instance>.service-now.com Connection: close Content-Length: 152 <request><entry> <name>user0</name> <id>1234</id> </entry> <entry> <name>user1</name> <id>5678</id> </entry> </request> |
[Table 1. Requests]

{#r_ScriptedRESTServiceScriptExamples__table_xkb_2vq_xs}

## Responses

Both requests specify application/json as the Accept header value. This causes either response to use JSON formatting, even if the request content type is XML.

    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8
    Transfer-Encoding: chunked
    Date: Tue, 04 Aug 2015 15:20:44 GMT
    Server: ServiceNow
    Connection: close
    Set-Cookie: BIGipServerpool_<Instance>=880838154.47166.0000; path=/

    {"result":{"id":1234,"id1":5678,"name":"user0","name1":"user1"}}


