CLion 2021.1 Help

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.

### Check response status, headers, and content-type GET https://httpbin.org/get > {% client.test("Request executed successfully", function() { client.assert(response.status === 200, "Response status is not 200"); }); client.test("Headers option exists", function() { client.assert(response.body.hasOwnProperty("headers"), "Cannot find 'headers' option in response"); }); client.test("Response content-type is json", function() { var type = response.contentType.mimeType; client.assert(type === "application/json", "Expected 'application/json' but received '" + type + "'"); }); %}

Working with environment variables

In this example, we'll capture a value from the received response into an environment 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.

POST https://httpbin.org/post Content-Type: application/json { "token": "my-secret-token" } //Saving a variable > {% client.global.set("auth_token", response.body.json.token); %}

After the request is executed, the auth_token variable can be accessed from both subsequent requests as {{auth_token}} and response handler scripts by means of the client.global.get("auth_token") construction.

//Accessing a variable GET https://httpbin.org/headers Authorization: Bearer {{auth_token}}

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.

POST https://httpbin.org/cookies //Saving a cookie from the first Set-Cookie header > {% client.global.set("my_cookie", response.headers.valuesOf("Set-Cookie")[0]); %}
Last modified: 19 May 2021