REST API Plugin

The plugin provides the following abilities:

  • build and send HTTP requests

  • validate HTTP responses (headers, status code, body)

  • validate JSON content of HTTP response bodies

Installation

Example 1. build.gradle
implementation(group: 'org.vividus', name: 'vividus-plugin-rest-api', version: '0.4.16')

Properties

Property Name Acceptable values Default Description

Configuration of REST API client

rest-api.http.endpoint

URL

<empty>

The base request endpoint

rest-api.http.header.

key-value mapping

<empty>

The property family to set HTTP headers for all outgoing requests, e.g. rest-api.http.header.my-sample-header=my-sample-value

See HTTP configuration for more fine-grained control over the HTTP interactions.

Expressions

The expression parameters marked with bold are mandatory.

removeWrappingDoubleQuotes

When REST API providing the data in JSON format is used it may be required to extract some values from JSON messages. String values are usually wrapped into double quotes, but sometimes only the value without quotes is needed. This expression allows to remove wrapping double quotes and use the value as is.

#{removeWrappingDoubleQuotes($input)}
  • $input - any string to remove wrapping double quotes

Example 2. Extracting ID from JSON data and using it in HTTP GET
When I save a JSON element from '${response}' by JSON path '$.id' to story variable 'id'
When I send HTTP GET to the relative URL 'rest/#{removeWrappingDoubleQuotes(${id})}'
Table 1. Examples of the expressions removing wrapping double quotes
Expression Result

#{removeWrappingDoubleQuotes("value")}

value

#{removeWrappingDoubleQuotes(value)}

value

#{removeWrappingDoubleQuotes()}

<empty>

#{removeWrappingDoubleQuotes("")}

<empty>

#{removeWrappingDoubleQuotes(""")}

"

#{removeWrappingDoubleQuotes("value)}

"value

#{removeWrappingDoubleQuotes(v"alu"e)}

v"alu"e

#{removeWrappingDoubleQuotes("va"lu"e")}

va"lu"e

#{removeWrappingDoubleQuotes("va"lu"e)}

"va"lu"e

#{removeWrappingDoubleQuotes("va"lue)}

"va"lue

#{removeWrappingDoubleQuotes(va"lue")}

va"lue"

encodeUriXyz

#{encodeUriXyz(..)} is a family of expressions that encode specific URI components (e.g. path, query) by percent encoding illegal characters, which includes non-US-ASCII characters, and also characters that are otherwise illegal within the given URI component type, as defined in RFC 3986.

Syntax Description

#{encodeUriUserInfo($userInfo)}

encodes the given URI user info

#{encodeUriHost($host)}

encodes the given URI host

#{encodeUriPath($path)}

encodes the given URI path

#{encodeUriPathSegment($segment)}

encodes the given URI path segment

#{encodeUriQuery($query)}

encodes the given URI query

#{encodeUriQueryParameter($queryParameter)}

encodes the given URI query parameter

#{encodeUriFragment($fragment)}

encode the given URI fragment

Table 2. Examples of the expressions encoding URI parts
Expression Result

#{encodeUriUserInfo(user@vividus.dev:pass)}

user%40vividus.dev:pass

#{encodeUriHost(vividus.бел)}

vividus.%D0%B1%D0%B5%D0%BB

#{encodeUriPath(/path/with spaces/)}

/path/with%20spaces/

#{encodeUriPathSegment(path/segment)}

path%2Fsegment

#{encodeUriQuery(a&b=c d)}

a&b=c%20d

#{encodeUriQueryParameter(a&b)}

a%26b

#{encodeUriFragment(frag ment)}

frag%20ment

Dynamic variables

Response

Provides payload of the latest response as string.

Variable name

${response}
Example 3. Validate response matches pattern
Then `${response}` matches `.+Home.+`

Response code

Variable name

${response-code}
Example 4. Validate response code
When I send HTTP GET to the relative URL '/get?name=Content'
Then `${response-code}` is equal to `200`

Response as binary data

Provides payload of the latest response body as binary data.

Variable name

${response-as-bytes}
Example 5. Save excel into temp folder
When I issue a HTTP GET request for a resource with the URL 'https://github.com/vividus-framework/vividus/blob/master/vividus-plugin-excel/src/test/resources/TestTemplate.xlsx?raw=true'
Then the response code is = '200'
When I create temporary file with name `excel` and content `${response-as-bytes}` and put path to SCENARIO variable `excelPath`

HTTP Steps

Set HTTP request configuration

Set up custom request configuration.

When I set HTTP request configuration:$configItems
  • $configItems - Table representing list of configuration items with columns "name" and "value" specifying their names and values respectively.

    Table 3. Available configs
    Config Acceptable values Request config default value Description

    expectContinueEnabled

    Boolean

    false

    Whether the 'Expect: 100-Continue' handshake is enabled

    staleConnectionCheckEnabled

    Boolean

    false

    Whether stale connection check is to be used

    redirectsEnabled

    Boolean

    true

    Whether redirects should be handled automatically

    relativeRedirectsAllowed

    Boolean

    true

    Whether relative redirects should be rejected

    circularRedirectsAllowed

    Boolean

    false

    Whether "circular redirects" (redirects to the same location) should be allowed

    authenticationEnabled

    Boolean

    true

    Whether authentication should be handled automatically

    contentCompressionEnabled

    Boolean

    true

    Whether the target server is requested to compress content

    normalizeUri

    Boolean

    true

    Whether client should normalize URIs in requests or not

    maxRedirects

    Integer

    50

    The maximum number of redirects to be followed

    connectionRequestTimeout

    Integer

    -1

    The timeout in milliseconds used when requesting a connection from the connection manager

    socketTimeout

    Integer

    -1

    The socket timeout in milliseconds

    socketTimeout

    Integer

    -1

    The socket timeout in milliseconds, which is the timeout for waiting for data or, put differently, a maximum period inactivity between two consecutive data packets

    cookieSpec

    String

    null

    The name of the cookie specification to be used for HTTP state management

* -1 means "infinity"

Example 6. Load a page with slow connection and with the property http.socket-timeout set to 15000
When I set HTTP request configuration:
|socketTimeout |
|25000         |
When I execute HTTP GET request for resource with URL `http://vividus-test-site.herokuapp.com/delayedLoading?pageTimeout=20000`
Then '${responseStatusCode}' is = '200'

Set HTTP request body

Sets HTTP request body that will be used while executing the request. In the case of textual content the default HTTP request header with name Content-Type and value text/plain; charset=UTF-8 is set.

No HTTP request header is set in the case of binary content.
Given request body: $content
  • $content - HTTP request body.

Example 7. Set textual HTTP request body
Given request body: Hello!
Example 8. Set binary HTTP request body
Given request body: #{loadBinaryResource(/data/image.png)}
When I set request headers:
|name        |value    |
|Content-Type|image/png|
When I send HTTP POST to the relative URL '/upload/png'

Prepare multipart HTTP request

Sets multipart request entity that will be used while executing HTTP requests.

Given multipart request:$requestParts

where requestParts is ExamplesTable representing the list of the request parts with the following columns:

  • type - One of request part types: STRING, FILE, BINARY.

  • name - The request part name.

  • value -

    • For FILE part type - the resource name or the file path.

    • For STRING or BINARY part type - the actual content.

  • contentType - The content type.

  • fileName - The name of the file contained in this request part. The parameter is not allowed for STRING part type, but it’s required for BINARY one and optional for FILE part type.

Example 9. Init HTTP request consisting of 4 different parts
When I initialize the scenario variable `temp-file-content` with value `Your first and last stop for No-Code Test Automation!`
When I create temporary file with name `abc.txt` and content `${temp-file-content}` and put path to scenario variable `temp-file-path`
Given multipart request:
|type  |name      |value            |contentType|fileName       |
|file  |file-key  |/data/file.txt   |           |anotherName.txt|
|file  |file-key2 |${temp-file-path}|text/plain |               |
|string|string-key|string1          |text/plain |               |
|binary|binary-key|raw              |text/plain |raw.txt        |

Set form data HTTP request

Sets URL-encoded form data request entity that will be used while executing HTTP requests. Default HTTP request header with name Content-Type and value application/x-www-form-urlencoded; charset=UTF-8 is set. In case if Content-Type is text/plain Set HTTP request body should be used

Given form data request:$parameters
  • $parameters - ExamplesTable representing list of parameters with columns name and value specifying form data request.

Example 10. Set ExamplesTable HTTP request body
Given form data request:
|name     |value  |
|firstName|Ivan   |
|lastName |Ivanov |
|password |!@3qwer|

Add HTTP headers to the request

Adds HTTP headers to the HTTP request.

When I add request headers:$headers
  • headers - ExamplesTable representing the list of the headers with columns name and value specifying HTTP header

Example 11. Add request header with name Accept-Language and value en-ru
When I add request headers:
|name           |value |
|Accept-Language|en-ru |
When I send HTTP GET to the relative URL '/get?name=Content'
Then a JSON element by the JSON path '$.headers.Accept-Language' is equal to '"en-ru"'

Execute HTTP request

Executes the HTTP request to access a resource on the server identified by the URL.

The step uses previously set HTTP headers and request body.

The response HTTP headers, response status code and response body can be accessed by the corresponding steps and dynamic variables.

When I execute HTTP $httpMethod request for resource with URL `$url`
  • $httpMethod - The HTTP method.

  • $url - The URL of the resource on the server.

Example 12. Execute HTTP GET request
When I execute HTTP GET request for resource with URL `https://example.com`

Wait for JSON element in the HTTP response

Waits for a specified amount of time until HTTP response body contains an element by the specified JSON path. The actions of the step:

  1. Execute sub-steps.

  2. Check if the HTTP response is present and the response body contains an element by JSON path.

  3. If the required JSON element exists or the maximum number of retries is reached, then the execution stops, otherwise the step actions are repeated.

  4. Stop step execution if HTTP response is not present or JSON element is found, otherwise sleep for the calculated part of specified duration and repeat actions from the start.

When I wait for presence of element by `$jsonPath` for `$duration` duration retrying $retryTimes times$stepsToExecute
  • $jsonPath - The JSON path of the element to find.

  • $duration - The time duration to wait in ISO-8601 format.

  • $retryTimes - The maximum of attempts. duration/retryTimes = timeout is a polling timeout between requests.

  • $stepsToExecute - The sub-steps to execute at each iteration.

Example 13. Wait for presence of element 10 times with polling timeout between requests 5 seconds
When I wait for presence of element by `$.unstableElement` for `PT50S` duration retrying 10 times
|step                                                                                    |
|When I execute HTTP GET request for resource with URL `http://example.com/testing-page` |

Wait for JSON element in the HTTP response with polling interval

Executes the provided sub-steps until the HTTP response body contains an element by the specified JSON path or the maximum number of retries is reached. The maximum duration of the step execution is not limited. The actions of the step:

  1. execute sub-steps

  2. wait the polling interval

  3. if the required JSON element exists or the maximum number of retries is reached, then the execution stops, otherwise the step actions are repeated

When I wait for presence of element by `$jsonPath` with `$pollingInterval` polling interval retrying $retryTimes times$stepsToExecute
  • jsonPath - the JSON path of the element to find

  • pollingInterval - the duration to wait between retries

  • retryTimes - the maximum number of the retries

  • stepsToExecute - the sub-steps to execute at each iteration

Example 14. Wait for presence of element by JSON path $.data.testData
When I wait for presence of element by `$.data.testData` with `PT5S` polling interval retrying 10 times
|step                                  |
|When I set request headers:           |
|{headerSeparator=!,valueSeparator=!}  |
|!name          !value                !|
|!Authorization !${accessToken}       !|
|When I issue a HTTP GET request for a resource with the URL '${requestUrl}'|

Validate secure protocols supported by server

Checks that a server defined by the hostname supports secure protocols listed in the protocols parameter.

Then server `$hostname` supports secure protocols that $rule `$protocols`
Example 15. Validate the server supports TLSv1.2 and TLSv1.3 protocols
Then server `vividus-test-site.herokuapp.com` supports secure protocols that contain `TLSv1.2,TLSv1.3`

Wait for expected HTTP status code in response

Waits for the specified number of times until HTTP response code is equal to the expected one. In case if the expected code is not returned after all retries, the assertion error will be recorded.

When I wait for response code $responseCode for $duration duration retrying $retryTimes times$stepsToExecute
  • $responseCode - The expected HTTP status code.

  • $duration - The time duration to wait in ISO-8601 format.

  • $retryTimes - The number of times the request will be retried: duration/retryTimes = timeout is a polling timeout between requests.

  • $stepsToExecute - The steps to execute at each wait iteration.

Example 16. Wait until HTTP GET request returns status code 200
When I wait for response code `200` for `PT10S` duration retrying 3 times
|step                                                        |
|When I send HTTP GET to the relative URL '/delayed-resource'|

Validate content type of response body

Checks content type of HTTP response body matches to the specified expected content type according to the provided string validation rule.

Then content type of response body $comparisonRule `$contentType`
Example 17. Submit a GET request and check that response body type is application/json
When I execute HTTP GET request for resource with URL `https://httpbin.org/json`
Then content type of response body is equal to `application/json`

Validate size of response body

Compare size of decompressed HTTP response body with the specified expected size in bytes.

Then size of decompressed response body is $comparisonRule `$sizeInBytes`
  • $comparisonRule - The comparison rule.

  • $sizeInBytes - The expected size of the response body in bytes.

Example 18. Submit a GET request and check that response body size is greater or equal to 1200 bytes
When I execute HTTP GET request for resource with URL `https://example.com`
Then size of decompressed response body is greater than or equal to `1200`

Save ZIP archive entries

Saves specified archive entries into varaibles.

When I save content of `$archiveData` archive entries to variables:$parameters
  • $archiveData - The archive data to verify.

  • $parameters - The ExampleTable that contains specified string comparison path, variableName, scopes, outputFormat. Available columns:

Example 19. Save archive entries
When I execute HTTP GET request for resource with URL `https://example.com/get-zip-archive`
When I save content of `${response-as-bytes}` archive entries to variables:
|path                     |variableName|scopes  |outputFormat|
|txtFileFromZipArchive.txt|text        |SCENARIO|TEXT        |
|txtFileFromZipArchive.txt|base64      |SCENARIO|BASE64      |
Then `${text}` is = `Response text from ZIP archive`
Then `${base64}` is = `UmVzcG9uc2UgdGV4dCBmcm9tIFpJUCBhcmNoaXZl`

Validate archive from response body

Step is deprecated and will be removed in VIVIDUS 0.5.0. Use instead Validate ZIP archive

Verifies that at least one (or no one) entry in a response archive matches the specified string comparison rule. If comparison rule column does not exist, the verification that archive entries have the specified names is performed.

Then response archive contains entries with names:$parameters
  • $parameters - The ExampleTable that contains specified string comparison rule and entry name pattern that should be found using current rule. Available columns:

Entry name in archive is not always the same as file name. Entry name reflects the full relative path from archive root.
Example 20. Submit a GET request and check that response archive has file with extension 'data' in 'data' folder but don’t contain any data file with name 'restrictedData'
When I execute HTTP GET request for resource with URL `https://example.com/get-zip-archive`
Then response archive contains entries with names:
|rule             |name                     |
|matches          |data/.+\.data            |
|does not contain |restrictedData.data      |
Example 21. Submit a GET request and check that response archive has file with name responseTextFromZipArchive.txt
When I execute HTTP GET request for resource with URL `https://example.com/get-zip-archive`
Then response archive contains entries with names:
|name                           |
|responseTextFromZipArchive.txt |

Validate ZIP archive

Verifies that at least one (or no one) entry in an archive matches the specified string comparison rule. If comparison rule column does not exist, the verification that archive entries have the specified names is performed.

Then `$archiveData` archive contains entries with names:$parameters
  • $archiveData - The archive data to verify.

  • $parameters - The ExampleTable that contains specified string comparison rule and entry name pattern that should be found using current rule. Available columns:

Entry name in archive is not always the same as file name. Entry name reflects the full relative path from archive root.
Example 22. Submit a GET request and check that response archive has file with extension 'data' in 'data' folder but don’t contain any data file with name 'restrictedData'
When I execute HTTP GET request for resource with URL `https://example.com/get-zip-archive`
Then `${response-as-bytes}` archive contains entries with names:
|rule             |name                     |
|matches          |data/.+\.data            |
|does not contain |restrictedData.data      |
Example 23. Submit a GET request and check that response archive has file with name responseTextFromZipArchive.txt
When I execute HTTP GET request for resource with URL `https://example.com/get-zip-archive`
Then `${response-as-bytes}` archive contains entries with names:
|name                           |
|responseTextFromZipArchive.txt |

Saves cookie to scope variable. If present several cookies with the same name will be saved cookie with the root path value (path is '/').

When I save value of HTTP cookie with name `$cookieName` to $scopes variable `$variableName`
Example 24. Get cookie with name cookieName and save its value to scenario variable value
When I issue a HTTP GET request for a resource with the URL 'https://httpbin.org/cookies/set/cookieName/cookieValue'
When I save value of HTTP cookie with name `cookieName` to scenario variable `value`
Then '${value}' is equal to 'cookieValue'

Change value of all HTTP cookies

Change cookie value. If several cookies with the same name exist in cookie store, the value will be changed for all of them.

When I change value of all HTTP cookies with name `$cookieName` to `$newCookieValue`
  • $cookieName - The name of cookie.

  • $newCookieValue - The new value for $cookieName.

Example 25. Get cookie with name cookieName and set new value for it newCookieValue
When I execute HTTP GET request for resource with URL `https://httpbin.org/cookies/set/cookieName/cookieValue`
When I change value of all HTTP cookies with name `cookieName` to `newCookieValue`
When I save value of HTTP cookie with name `cookieName` to scenario variable `value`
Then '${value}' is equal to 'newCookieValue'

JSON Steps

Verify context contains data

Checks if the JSON context contains an expected data by a JSON path

Then JSON element by JSON path `$jsonPath` is equal to `$expectedData`$options
Example 26. Check JSON context contains JSON object by JSON path
Then JSON element by JSON path `$.accountList[0]` is equal to `
{
  "accountId": 12345,
  "accountName": "${json-unit.any-string}",
  "status": "Active"
}
`ignoring extra fields

Verify JSON contains data

Checks if a JSON contains an expected data by a JSON path

Then JSON element from `$json` by JSON path `$jsonPath` is equal to `$expectedData`$options
  • json - input JSON

  • jsonPath - JSON Path

  • expectedData - expected JSON

  • options - options

Example 27. Check JSON contains string value by JSON path
Then JSON element from `
{
  "accountId": 12345,
  "status": "Active"
}
` by JSON path `$.status` is equal to `Active`

Verify number of elements in context

Verifies that the number of elements found in the JSON context by a JSON path matches an expected number according to specified comparison rule

Then number of JSON elements by JSON path `$jsonPath` is $comparisonRule $elementsNumber
Example 28. Number of account lists in JSON is equal to 2
Then number of JSON elements by JSON path `$.accountList` is equal to 2

Verify number of elements in JSON

Verifies that the number of elements found in JSON data by a JSON path matches an expected number according to specified comparison rule

Then number of JSON elements from `$json` by JSON path `$jsonPath` is $comparisonRule $elementsNumber
Example 29. Number of account lists in JSON is equal to 2
Then number of JSON elements from `
[
  {
    "accountId": 843
  },
  {
    "accountId": 233
  }
]
` by JSON path `$..accountId` is equal to 2

Save element from context

Saves value extracted from the JSON context into a variable with specified name

When I save JSON element from context by JSON path `$jsonPath` to $scopes variable `$variableName`
Example 30. Save accountId element from JSON context
When I save JSON element from context by JSON path `$.accountId` to SCENARIO variable `account-id`

Save element from JSON

Saves value extracted from a JSON data into a variable with specified name

When I save JSON element from `$json` by JSON path `$jsonPath` to $scopes variable `$variableName`
Example 31. Save accountId element from JSON
When I save JSON element from `
{
  "accountId": 12345,
  "status": "Active"
}
` by JSON path `$.accountId` to SCENARIO variable `account-id`

Save number of elements in context

Saves number of elements found in the JSON context by JSON path into a variable

When I set number of elements found by JSON path `$jsonPath` to $scopes variable `$variableName`
Example 32. Save number of id elements
When I set number of elements found by JSON path `$..id` to scenario variable `idsCount`

Save number of elements from JSON

Saves number of elements found in the JSON by JSON path into a variable

When I save number of elements from `$json` found by JSON path `$jsonPath` to $scopes variable `$variableName`
Example 33. Save number of elements from the JSON
When I save number of elements from `[{"key" : "passed"}, {"key" : "failed"}]` found by JSON path `$..[?(@.key == "failed")]` to scenario variable `messageCount`

Validate HTTP resources

Validates the defined HTTP resources

Actions performed by step:

  • executes HTTP HEAD request against the passed URL

  • if the status code is 200 then the check is considered as passed

  • if the status code falls under any of 404, 405, 501, 503 then the HTTP GET request will be sent

  • if the GET status code is 200 then check is considered as passed, otherwise failed

  • if the target URL had beed already checked then the check is considered as skipped

Then HTTP resources are valid:$resources
  • resources - The URLs of HTTP resources to validate

Example 34. Verify HTTP resources
Then HTTP resources are valid:
|url                                                    |
|https://saucelabs.com                                  |
|https://vividus-test-site.herokuapp.com/img/vividus.png|