OBLYTECH Logo
OBLYTECH Logo

RESTMessageV2 and SOAPMessageV2 Scripting APIs

RESTMessageV2 and SOAPMessageV2 are the classes ServiceNow scripts use to send outbound REST and SOAP requests. You configure the request with setter methods, send it with execute or executeAsync, and read the status, body, headers and errors from the response object. Attachments, MID servers and stored credentials use the same sequence.

Where these classes run and how you create them

The REST and SOAP classes live in the sn_ws namespace and work in both scoped applications and the global scope, so a business rule can call them. For the concept behind outbound calls, start with the outbound REST overview.

Requests carry a User-Agent of ServiceNow/1.0 by default. To change it across the instance’s calls, set the glide.http.user.agent system property instead of adding a header in each script.

The no-argument RESTMessageV2 constructor gives you an empty message, so you must set the method and endpoint yourself. The other form takes a REST message record name and a method name such as get or put; method names are case insensitive. Record values act as defaults that setter methods can override. If the record is missing or not visible from your script’s scope, the constructor can throw, so wrap it in a try block.

Setting up the request before you send it

Setter methods return nothing, so call them in sequence before execute. The main ones are:

Method What it controls
setEndpoint(endpoint) Target URL; required with the empty constructor
setHttpMethod(method) GET, POST, PUT, PATCH, DELETE or HEAD
setRequestHeader(name, value) One outbound header, such as Accept
setRequestBody(body) Body for PUT and POST; record variables are not substituted
setRequestBodyFromAttachment(sysId) Sends an existing attachment record as the body
setQueryParameter(name, value) Appends name=value to the URL
setStringParameter / setStringParameterNoEscape Fills a record variable, with or without XML escaping
setBasicAuth(userName, password) Basic auth headers, overriding the record
setAuthenticationProfile(type, profileId) A stored basic or OAuth 2.0 profile by sys_id
setHttpTimeout(milliseconds) Socket timeout for the call
setLogLevel(level) basic, elevated or all

Watch two details. setRequestBody sends the text exactly as written, so build the full XML or JSON string yourself. Use setStringParameterNoEscape when the value contains markup that must not be escaped. If a response is truncated and your request contains curly brackets or dollar signs, call disableForcedVariableSubstitution before execute.

The timeout counts silence on the socket, so a slow stream that keeps delivering data can run past the figure you set.

Choosing between execute, executeAsync and a MID server

execute waits for the provider and holds the script thread while it does, so keep it for quick calls rather than high volume. executeAsync returns without waiting, so the result is handled elsewhere, usually in a business rule that runs when the reply arrives.

Messages routed through a MID server are asynchronous and travel through the External Communication Channel queue. That route reaches endpoints behind a firewall or on a private network. Call setMIDServer with the name of the MID server, and setEccCorrelator with a unique value per request so each reply can be matched to its request.

waitForResponse(seconds) pauses for a queued reply and overrides the ECC response timeout for that response. It is handy for testing a connection, but a business rule that handles the reply keeps the script free.

Three example patterns and what each shows

The recordless pattern builds the whole message in the script: an empty object, basic auth, a POST method, an endpoint on an incident table path in the table API endpoint format, and a JSON body with a short description. Use it when the message belongs to the script rather than to a stored record.

The direct pattern starts from a named record with a GET method, sets a record variable and an unescaped XML variable, sets a ten second timeout, and checks haveError before reading the error or the body. A finally block reads the request body, so logs show what was sent even when the call fails.

The MID server pattern adds setMIDServer, switches to executeAsync, and waits up to sixty seconds for the queue response. Treat it as a learning example. In production, the body handling usually belongs in its own rule.

Reading the response object

execute and executeAsync return a RESTResponseV2 object. The main methods are:

  • getStatusCode: the HTTP status number, such as 200.
  • getBody: the body as text.
  • haveError and getErrorMessage: whether the transaction failed, and why.
  • getErrorCode: a platform number, such as 1 for a socket timeout. It is not an HTTP code.
  • getHeader, getHeaders and getAllHeaders: one value, a map that keeps the last copy of a repeated header, or a list with each copy.
  • getCookies: the cookies as an array of strings.
  • getQueryString: the resolved query, for direct requests.
  • getResponseAttachmentSysid: the sys_id of an attachment made from the body.

Check haveError before trusting the status, because a transaction can fail on the platform side. When a response sets several cookies, use getAllHeaders.

Saving a response as an attachment

saveResponseBodyAsAttachment takes a table name, a record sys_id and a file name, and stores the reply on that record. A fourth argument, an encryption context sys_id, stores it encrypted. JSON and XML replies can be saved as well as binary files. Call the method before execute.

Afterwards, getBody raises an error, so read the new attachment through getResponseAttachmentSysid instead. With a MID server, the MID server user needs roles to write attachments and to write records on the target table. If saving fails, read getErrorMessage.

Working with SOAPMessageV2

The empty SOAPMessageV2 constructor requires setSOAPAction and setEndpoint. The record form takes a SOAP message record and a function name from its WSDL, and inherits the endpoint, authentication and MID server settings from the record.

Setter methods mirror the REST side. setRequestBody takes the full envelope, while setBasicAuth and setRequestHeader work the same way. setWSSecurity takes a key store sys_id, an alias, a password and a trusted certificate sys_id, and it overwrites stored WS-Security values. Redirects are off by default, so a 3xx status comes back unless you enable setFollowRedirect.

execute is synchronous and suits quick calls. By default, glide.http.timeout is 175 seconds and glide.http.connection_timeout is 10 seconds. Do not use execute for MID server routes, because the thread would then wait on the queue. executeAsync queues the message for the SOAPClient business rule, which runs synchronously by default. To change that, set its When value to Async and add current.update() to the end of its script.

SOAPResponseV2 reads the same way as the REST response object. waitForResponse(seconds) overrides the glide.soap.outbound.ecc_response.timeout property for that one response.

Using GlideHTTPRequest in global scripts

GlideHTTPRequest takes an endpoint in its constructor and offers short methods: addHeader, addParameter, setBasicAuth, setContentType, setHttpTimeout in milliseconds, setupProxy with a host and port, and get and post. Follow-redirect is on by default here, and the log level defaults to basic. Use JSON.parse for JSON bodies and gs.xmlToJSON for XML, switching the Accept header to change the format.

The class is meant for global server-side scripts, while RESTMessageV2 and SOAPMessageV2 work in scoped and global code. In a scoped application, the sn_ws classes are the practical choice.

Logging and troubleshooting outbound calls

Log levels run from basic, which records host, path and status, through elevated, which adds headers and the query string, to all, which adds bodies. A setLogLevel call overrides the record level, though excluded domains or the glide.outbound_http_log.override property can prevent that. Entries appear under System Logs, Outbound HTTP Requests.

Platform-added headers stay out of getRequestHeader and getRequestHeaders until glide.http.log_debug is true.

Common fixes:

  • Truncated output with brackets or dollar signs: call disableForcedVariableSubstitution.
  • Missing record: check the record name and the script’s scope.
  • Overlong MID server endpoint: override the source value with setEccParameter.
  • Failed attachment save: read getErrorMessage on the response.

Frequently asked questions

Which class should a REST call use?

RESTMessageV2, because it works in scoped and global code and supports both record-based and recordless construction. GlideHTTPRequest suits global scripts that prefer a short style. Pick one per integration so the pattern stays consistent.

Why does getBody fail after I saved an attachment?

Saving the reply changes how the body is handled, so read the attachment’s sys_id with getResponseAttachmentSysid instead.

Does executeAsync return the answer immediately?

No. Handle the reply in a business rule, or use waitForResponse if a short pause is acceptable.

What is the difference between getHeaders and getAllHeaders?

getHeaders keeps the last copy of a repeated header. getAllHeaders keeps each copy, which matters when a response sets several cookies.

What does getErrorCode tell me?

It is a platform number, not an HTTP status. A value of 1 means a socket timeout. Keep the number when you contact support, since it helps identify the failure.