Response handling examples
In this topic, we'll examine a couple of HTTP response handling examples. To try examples yourself, explore the auth-requests and test-responses requests collections.
Checking response headers, body, and content type
In this example, we'll create several tests to verify the following:
The request is executed successfully, that is, the response status is 200.
Headers are received within the response body.
The response's content type is application/json.
To create a test, we call the test
method of the client object. Inside the test, we can assert a specific condition by calling the assert
method of the client
object and refer to various properties of the response object to validate them.
Use global variables
In this example, we'll capture a value from the received response into a global variable, which can be then used in subsequent requests.
The first request involves a response handler script, which saves an authentication token from the received response body into the auth_token
variable under client.global. To achieve this, we use the client.global.set(VariableName, VariableValue)
construction. As the VariableValue
argument, we use the value of the token
field from the response body returned by the server. This value is then assigned to the "auth_token"
variable.
After the request is executed, the auth_token
variable can be accessed from subsequent requests (in the {{auth_token}}
variable) and response handler scripts (by means of the client.global.get("auth_token")
construction).
To obtain a value from a response header, use the valueOf
method of the headers object. If several headers with the same name are received (which is a common case for the Set-Cookie header), use the valuesOf
method instead. This will return an array of all response header values.
Process each line of an event stream
If you subscribe to an event stream, a server will automatically send events to your client when new data becomes available. This data can be in the form of Server-Sent Events or newline-delimited JSON (NDJSON). In JetBrains Rider, you can use the HTTP Client response.body.onEachLine method to call a function on each line of this event stream.
Suppose you have a server that regularly sends information on the gold price. In this example, let's write a response handler script, which does the following:
Takes each chunk of data (JSON object) received from the server and logs the price value. When you run the request, you can view the logged info in the Response Handler tab of the Services tool window.
Stops processing the received data when the number of events exceeds 10. Note that this does not unsubscribe you from the event stream – you'll keep receiving events as long as the HTTP connection is open (check the Console tab of the Services tool window).
Tests the obtained chunks of data: if the price is less than 45, the test fails. You can view the test results in the Tests tab of the Services tool window.