Scripted REST API example - script samples
Summarize
Summary of Scripted REST API example - script samples
This documentation provides practical examples for creating and handling scripted REST API resource scripts in ServiceNow. It covers how to process different types of requests, extract parameters, handle errors, and format responses. These examples help you build robust and reusable REST APIs tailored to your enterprise needs.
Show less
Handling Request Parameters
- Query Parameters (GET): Extract query parameter values and custom headers from the request.
- Path Parameters (GET): Access path parameters from the request URI.
- Script Include (GET): Utilize script includes to maintain common code for generating responses, promoting reusability and readability in scripts.
Request Body Processing
- String POST: Parse string data from the POST request body and return it in the response.
- Binary POST: Handle binary data in POST requests, enabling actions like record insertion based on the binary content.
- Scripted REST Resource Example: Parse JSON or XML request bodies containing arrays of objects, extract specific fields (e.g., name and id), and return a structured JSON response.
Error Handling Examples
The examples demonstrate how to return appropriate HTTP error responses based on different failure scenarios:
- Not Acceptable Error (406): When the Accept header is unsupported.
- Bad Request Error (400): For invalid request syntax.
- Conflict Error (409): For conflicting requests, such as simultaneous updates.
- Not Found Error (404): When the requested resource is unavailable.
- Unsupported Media Type Error (415): When the request Content-Type is unsupported.
- Custom Service Error: Define custom status codes, messages, and details beyond standard errors.
Best Practices and Common Pitfalls
- Always wrap functions in parentheses to avoid syntax errors.
- Avoid setting or returning the request or response objects directly in the response body to prevent serialization errors.
Request and Response Formats
The API supports both JSON and XML request payloads. Regardless of whether the request content is JSON or XML, the response format is controlled by the Accept header and commonly returned as JSON.
- Example JSON Request: An array of objects with
nameandidfields. - Example XML Request: Equivalent data structured in XML format.
- Response: JSON formatted response containing parsed values from the request body.
Practical Value for ServiceNow Customers
These script samples enable you to efficiently implement REST APIs that handle various input types and error scenarios with clear, maintainable code. Understanding these examples helps you build integrations that correctly parse request data, handle errors gracefully, and return structured, consistent responses. This results in improved API reliability and easier maintenance within your ServiceNow environment.
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
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
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
/**
* 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
| JSON Request | XML Request |
|---|---|
|
|
Responses
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"}}