Scripted REST API example - streaming vs object serialization
-
- UpdatedAug 3, 2023
- 4 minutes to read
- Vancouver
- API implementation
These examples demonstrate how to send a JSON response using streaming and using default object serialization.
Streaming vs object serialization
When sending a response, you can send a response as a stream or serialize an object. There are advantages and disadvantages to either approach. Pick a technique based on the needs of your integration.
Generally, if the response object is simple, can be represented as XML or JSON, and is a consistent size, use object serialization. If using a format other than XML or JSON, or if the size of the response varies, use streaming.
Streaming the response
Using a streaming responses provides advantages in response time, instance performance, and content flexibility, but adds additional complexity to the script. When using streaming, you are responsible for formatting the response, setting the response status, and setting the Content-Type header. When streaming a response, the requesting user receives a response quickly because the entire response does not need to be created before starting streaming.
This example demonstrates a Scripted REST Resource script that returns an array of incident records using streaming.
Example
A request to this resource returns the following response.
Building an object
Using object serialization allows you to take advantage of ServiceNow provided serialization and content negotiation. When serializing an object instead of streaming, the entire object must be created and serialized before the client receives a response. This may delay the response, or require a large amount of system resources if the response object is very large. Object serialization is available only for XML or JSON responses. Responses using a different format must use streaming.
This example returns the same Incident data as the streaming example, but collects all of the response data in an array before sending the response.
Example
A request to this resource returns the following response.