{"revision":"c10276e953456835cdbb1f3a60d58ae1980be353","document":{"id":429,"path":"api-reference/rest-api-explorer/r_ScriptedRESTServiceScriptExamples.md","title":"Scripted REST API example - script samples","bundle":null,"doc_type":null,"release":"australia","body":"\n# Scripted REST API example - script samples\n\nThese examples demonstrate how to create various resource scripts for a scripted REST API.\n\n## Query parameters GET example\n\nThis example demonstrates how to get query parameter values from a request.\n\n```\n/**\n * GET - Sample Request API - Query Params\n */\n(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {\n    var uri = request.uri;\n    var url = request.url;\n    var queryParams = request.queryParams;\n    var customHeader = request.getHeader('X-Custom');\n\n    return {\n        \"uri\": uri,\n        \"url\": url,\n        \"queryParams\": queryParams,\n        \"customHeader\": customHeader\n    };\n\n})(request, response);\n```\n\n## Path parameters GET example\n\nThis example demonstrates how to get path parameter values from a request.\n\n```\n/**\n * GET - Sample Request API - Path Params\n */\n(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {\n    var uri = request.uri;\n    var url = request.url;\n    var path = request.pathParams;\n\n    return {\n        \"uri\": uri,\n        \"url\": url,\n        \"path_params\": path,\n        \"path.id\": path.id\n    };\n})(request, response);\n\n```\n\n## Script include GET example\n\nThis 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.\n\n```\n/**\n * GET - Sample Request API - Script Include\n */\n(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {\n    var responseObj = global.SampleDataUtil.getSampleJSON();\n    return responseObj;\n})(request, response);\n```\n\n## String POST example\n\nThis example demonstrates how to parse a POST message with a string body and send a response based on the request.\n\n```\n/**\n *  POST - Sample Request API - dataString\n *  sample usage:\n *  var requestBody = request.body;\n *  var requestString = requestBody.dataString;\n */\n(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {\n    var requestBody = request.body;\n    var requestString = requestBody.dataString;\n    return {\"requestString\": requestString};\n})(request, response);\n```\n\n## Binary POST example\n\nThis example demonstrates how to parse a POST message with a binary body and send a response based on the request.\n\n```\n/**\n * POST - Sample Request API - Body\n */\n(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {\n    var body = request.body.data;\n    //do any additional processing on the request body, such as inserting a new record.\n    return {\n        \"body.id\": body.id\n    };\n})(request, response);\n```\n\n## Not acceptable error example\n\nThis 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.\n\n```\n/**\n * Sample Not Acceptable Error Sample\n */\n(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {\n    response.setError(new sn_ws_err.NotAcceptableError('sample error message'));\n})(request, response);\n```\n\n## Bad request error example\n\nThis example demonstrates how to respond with a bad request error. Use this error type to indicate a mistake in the request syntax.\n\n```\n/**\n * Bad Request Error Sample\n */\n(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {\n    response.setError(new sn_ws_err.BadRequestError('sample error message'));\n})(request, response);\n```\n\n## Conflict error example\n\nThis 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.\n\n```\n/**\n * Error Response: Conflict Error Sample\n */\n(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {\n    response.setError(new sn_ws_err.ConflictError('sample error message'));\n})(request, response);\n```\n\n## Not found error example\n\nThis example demonstrates how to respond with a not found error. Use this error type if the requested resource does not exist or is unavailable.\n\n```\n/**\n * Error Response: Not Found Error Sample\n */\n(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {\n    response.setError(new sn_ws_err.NotFoundError('sample error message'));\n})(request, response);\n```\n\n## Unsupported media type error example\n\nThis 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.\n\n```\n/**\n * Error Response: Unsupported Media Type Error Sample\n */\n(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {\n    response.setError(new sn_ws_err.UnsupportedMediaTypeError('sample error message'));\n})(request, response);\n```\n\n## Service error example\n\nThis 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.\n\n```\n/**\n * Error Response: Custom Error Sample\n */\n(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {\n    var myError = new sn_ws_err.ServiceError();\n    myError.setStatus(418);\n    myError.setMessage(\"I am a Teapot\");\n    myError.setDetail(\"Here are the details about this error\");\n    response.setError(myError);\n})(request, response);\n\n```\n\n## Function parentheses error example\n\nThis example demonstrates that if a function is not wrapped in parentheses, it results in a error. Include parentheses with all functions.\n\n```\n(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {\n\tgs.info(\"message: {0}\", request.body.data.message);\n})(request, response);\n\nfunction test() {\n\tgs.info(\"test\");\n}(request, response);\n```\n\n## Serialization error example\n\nThis example demonstrates that if the request is set as a body to the response, it can result in a serialization error.\n\n```\nsetBody_request:\n    response.setBody(request);\n```\n\nThis example demonstrates that if the response is set as a body to the response, it can result in a serialization error.\n\n```\nsetBody_response:\n    response.setBody(response);\n```\n\nThis example demonstrates that if the request is returned, it can result in a serialization error.\n\n```\nreturn_request:\n    return request;\n```\n\nThis example demonstrates that if the response is returned, it can result in a serialization error.\n\n```\nreturn_response:\n    return response;\n```\n\n## Scripted REST resource script example\n\nThis sample REST API resource script parses the **name** and **id** values from the request body and returns those values in the response.\n\n```\n/**\n * POST - Sample Request API - Body\n */\n(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {\nvar body = request.body.data,\nid0,name0,id1,name1;\nname0 = body[0].name; // 'user0'\nid0 = body[0].id; // '1234'\nname1 = body[1].name; // 'user1'\nid1 = body[1].id; // '5678'\n\nreturn {\n\"id\": id0,\n\"name\": name0,\n\"id1\": id1,\n\"name1\": name1\n};\n})(request, response);\n```\n\n## Requests\n\nThe API can accept both XML and JSON requests.\n\n<table id=\"table_xkb_2vq_xs\"><thead><tr><th>\n\nJSON Request\n\n</th><th>\n\nXML Request\n\n</th></tr></thead><tbody><tr><td>\n\n```\nPOST /api/sn_demo_api/v1/example/body HTTP/1.1\nContent-Type: application/json\nAccept: application/json\nHost: <instance>.service-now.com\nConnection: close\nContent-Length: 91\n\n[   \n  { \"name\": \"user0\",\n    \"id\": 1234\n  },\n  {\n    \"name\": \"user1\",\n    \"id\": 5678\n  }\n]\n```\n\n</td><td>\n\n```\nPOST /api/sn_demo_api/v1/example/body HTTP/1.1\nContent-Type: application/xml\nAccept: application/json\nHost: <instance>.service-now.com\nConnection: close\nContent-Length: 152\n\n<request><entry>\n      <name>user0</name>\n      <id>1234</id>\n   </entry>\n   <entry>\n      <name>user1</name>\n      <id>5678</id>\n   </entry>\n</request>\n```\n\n</td></tr></tbody>\n</table>## Responses\n\nBoth 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.\n\n```\nHTTP/1.1 200 OK\nContent-Type: application/json;charset=UTF-8\nTransfer-Encoding: chunked\nDate: Tue, 04 Aug 2015 15:20:44 GMT\nServer: ServiceNow\nConnection: close\nSet-Cookie: BIGipServerpool_<Instance>=880838154.47166.0000; path=/\n\n{\"result\":{\"id\":1234,\"id1\":5678,\"name\":\"user0\",\"name1\":\"user1\"}}\n```\n\n**Parent Topic:**[Scripted REST API examples](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/rest-api-explorer/c_ScriptedRESTAPIExamples.md)\n\n"}}