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

  1. Copy the below line to dependencies section of the project build.gradle file

    Please make sure to use the same version for all VIVIDUS dependencies.
    Example 1. build.gradle
    implementation(group: 'org.vividus', name: 'vividus-plugin-rest-api', version: '0.6.4')
  2. If the project was imported to the IDE before adding new dependency, re-generate the configuration files for the used IDE and then refresh the project in the used IDE.

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

rest-api.http.extended-logging

true false

false

Enable logging of HTTP request/response headers and bodies (applied to the following content types only: text/*, application/json, application/xml)

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

Expressions

The expression parameters marked with bold are mandatory.

removeWrappingDoubleQuotes

The expression is deprecated and will be removed in VIVIDUS 0.7.0. Please use JSON steps validating and saving JSON element values instead

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 execute HTTP GET request for resource with 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

#{encodeUri($anyValue)}

Encodes all characters that are either illegal, or have any reserved meaning, anywhere within a URI, as defined in RFC 3986. This is useful to ensure that the given value will be preserved as-is and will not have any impact on the structure or meaning of the URI.

#{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( https://user@vividus.dev:vividus.dev/path/segment?a&b=c#fragment)}

https%3A%2F%2Fuser%40vividus.dev%3Avividus.dev %2Fpath%2Fsegment%3Fa%26b%3Dc%23fragment

#{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

HTTP response as text

The variable provides the HTTP response body of the latest executed HTTP call as string.

${response}
Example 3. Validate the HTTP response matches the regular expression
When I execute HTTP GET request for resource with relative URL `/get?name=Content`
Then `${response}` matches `.+Home.+`

HTTP response as binary data

The variable provides the HTTP response body of the latest executed HTTP call as binary data.

${response-as-bytes}
Example 4. Save the received Excel document into the temporary folder
When I execute HTTP GET request for resource with URL `https://github.com/vividus-framework/vividus/blob/master/vividus-plugin-excel/src/test/resources/TestTemplate.xlsx?raw=true`
When I create temporary file with name `excel` and content `${response-as-bytes}` and put path to scenario variable `excelPath`

HTTP response code

The variable provides the HTTP response status code of the latest executed HTTP call.

${response-code}
Example 5. Validate the HTTP response code
When I execute HTTP GET request for resource with relative URL `/get?name=Content`
Then `${response-code}` is equal to `200`

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
    Configuration item Acceptable values Default value Description

    expectContinueEnabled

    true
    false

    false

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

    redirectsEnabled

    true
    false

    true

    Whether redirects should be handled automatically

    circularRedirectsAllowed

    true
    false

    false

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

    authenticationEnabled

    true
    false

    true

    Whether authentication should be handled automatically

    contentCompressionEnabled

    true
    false

    true

    Whether the target server is requested to compress content

    maxRedirects

    Integer

    50

    The maximum number of redirects to be followed

    connectionRequestTimeout

    Integer (milliseconds)

    180000

    The timeout used when requesting a connection from the connection manager

    connectTimeout

    Integer (milliseconds)

    180000

    The timeout until a new connection is fully established

    responseTimeout

    Integer (milliseconds)

    0

    The timeout until arrival of a response from the opposite endpoint. A timeout value of zero is interpreted as an infinite timeout.

    cookieSpec

    • relaxed - The RFC 6265 compliant policy (interoperability profile).

    • strict - The RFC 6265 compliant policy (strict profile).

    • ignore - The policy that ignores cookies.

    <not set>

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

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 `https://vividus-test-site-a92k.onrender.com/?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
Example 7. Alias syntax
Given request body:`$content`
  • $content - HTTP request body.

Example 8. Set textual HTTP request body
Given request body: Hello!
Example 9. 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 execute HTTP POST request for resource with relative URL `/upload/png`
Example 10. Set an ampty string as HTTP request body
Given request body:``

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 11. Init HTTP request consisting of 4 different parts
Given I initialize 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 - The ExamplesTable representing list of parameters with columns name and value specifying form data request.

Example 12. Set form data 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 existing HTTP headers of the building HTTP request.

The added HTTP headers are scoped to the first performed HTTP request and not available afterwards.
When I add request headers:$headers
  • headers - The ExamplesTable representing the list of the headers with columns name and value specifying HTTP header.

Example 13. Add request header with name Accept-Language and value en-us
When I add request headers:
|name           |value |
|Accept-Language|en-us |
When I execute HTTP GET request for resource with relative URL `/get?name=Content`
When I save JSON element value from `${response}` by JSON path `$.headers.Accept-Language` to scenario variable `language`
Then `${language}` is equal to `"en-us"`

Set HTTP headers to the request

Sets HTTP headers to the building HTTP request. Previously set HTTP headers are discarded.

The added HTTP headers are scoped to the first performed HTTP request and not available afterwards.
When I set request headers:$headers
  • headers - The ExamplesTable representing the list of the headers with columns name and value specifying HTTP header.

Example 14. Set request header with name Content-Type and value application/json
When I set request headers:
|name        |value           |
|Content-Type|application/json|
Given request body: {
  "type": "article"
}
When I execute HTTP POST request for resource with URL `https://api.example.com/entries`

Execute HTTP request with absolute URL

Executes the HTTP request for a resource identified by the absolute URL. The step uses previously set HTTP headers and request body. The HTTP response headers, status code and 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 15. Execute HTTP GET request
When I execute HTTP GET request for resource with URL `https://example.com`

Execute HTTP request with relative URL

Executes the HTTP request for a resource identified by the URL relative to the base URL specified by the rest-api.http.endpoint property. The step uses previously set HTTP headers and request body. The HTTP response headers, status code and body can be accessed via the corresponding steps and dynamic variables.

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

  • $relativeURL - The relative URL of the resource on the server.

Example 16. Configuration
rest-api.http.endpoint=https://httpbin.org
Example 17. Execute HTTP GET request
When I execute HTTP GET request for resource with relative URL `/image/jpeg`

Compare HTTP response body against resource

Compares the HTTP response body against the resource data according to the provided rule.

Then response body $validationRule resource at `$resourcePath`
  • $validationRule - The validation rule, either is equal to or is not equal to.

  • $resourcePath - The resource path.

Example 18. Compare images
When I execute HTTP GET request for resource with URL `https://httpbin.org/image/png`
Then response body is equal to resource at `/images/pig.png`

Validate HTTP response code

Compares the HTTP response status code against the expected number.

Then response code is $comparisonRule `$responseCode`
Example 19. Validate the resource is not found
When I execute HTTP GET request for resource with URL `https://httpbin.org/cfa2fdbc`
Then response code is equal to `404`

Validate HTTP response time

Compares the HTTP response time against the expected number in milliseconds.

Then response time is $comparisonRule `$responseTime` milliseconds
  • $comparisonRule - The comparison rule.

  • $responseTime - The expected response time in milliseconds.

Example 20. Check HTTP response time
When I execute HTTP GET request for resource with URL `https://example.com`
Then response time is less than `1000` milliseconds

Valdate number of HTTP response headers

Validates the number of HTTP response headers filtered by the specified name.

Then number of response headers with name `$headerName` is $comparisonRule $number
Example 21. Check the browser is forced to use a secure web connection
Then number of response headers with name `Strict-Transport-Security` is equal to 1

Validate HTTP response header value

Compares the header value against the expected value according to the comparison rule.

Then value of response header `$headerName` $comparisonRule `$value`
Example 22. Check HTTP response content type
When I execute HTTP GET request for resource with URL `https://httpbin.org/robots.txt`
Then value of response header `Content-Type` is equal to `text/plain`

Validate HTTP response header elements

Validates that the response header with the specified name contains elements. Might be useful to verify such HTTP headers as Set-Cookie that have values that can be decomposed into multiple elements.

Example 23. HTTP header with elements format
header = [ element ] *( "," [ element ] )
Then response header `$headerName` contains elements:$elements
Example 24. Check attributes of Set-Cookie header
When I execute HTTP GET request for resource with URL `https://httpbin.org/authenticate`
Then response header `Set-Cookie` contains elements:
|element |
|JSESSION|
|clientId|

Save HTTP response header value

Saves the HTTP response header value into a variable.

When I save response header `$headerName` value to $scopes variable `$variableName`
Example 25. Save Content-Length header value
When I execute HTTP GET request for resource with URL `https://httpbin.org/brotli`
When I save response header `Content-Length` value to scenario variable `length`

Validate connection security

Validates that the HTTP connection is secured with the defined security protocol.

Then connection is secured using $securityProtocol protocol
  • $securityProtocol - The expected security protocol, e.g. TLSv1.2, TLSv1.3

Example 26. Check that the httpbin is secured
When I execute HTTP GET request for resource with URL `https://httpbin.org/`
Then connection is secured using TLSv1.2 protocol

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 Durations 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 27. 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 28. 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 execute HTTP GET request for resource with 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 29. Validate the server supports TLSv1.2 and TLSv1.3 protocols
Then server `vividus-test-site-a92k.onrender.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 Durations 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 30. 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 execute HTTP GET request for resource with 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 31. 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 absence of response body

Validates that the HTTP response does not contain a body.

Then response does not contain body
Example 32. Submit a POST request and check that response body is absent
When I execute HTTP POST request for resource with URL `https://httpbin.org/json`
Then response does not contain body

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 33. 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

The step is moved to core package i.e. it’s not required to install any plugin to use this step - it’s available out of the box.

Validate ZIP archive

The step is moved to core package i.e. it’s not required to install any plugin to use this step - it’s available out of the box.

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 has already been 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-a92k.onrender.com/img/vividus.png |

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 35. Get cookie with name cookieName and save its value to scenario variable value
When I execute HTTP GET request for resource with 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 36. 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 JSON contains data

The step is moved to vividus-plugin-json.

Verify number of elements in JSON

The step is moved to vividus-plugin-json.

Save element from JSON

The step is moved to vividus-plugin-json.

Save number of elements from JSON

The step is moved to vividus-plugin-json.

JWT steps

Generate JWT

Generates JSON Web Token (JWT) with header and payload signed with secret key using HmacSHA256 algorithm and saves the result to scope variable with the specified name.

When I generate JWT with header `$header` and payload `$payload` signed with key `$key` using HS256 algorithm and save result to $scopes variable `$variableName`
  • $header - The header of JWT.

  • $payload - The payload of JWT.

  • $key - Secret key used by HS256 algorithm to sign the token.

  • $scopes - The comma-separated set of the variables scopes.

  • $variableName - The name of variable to save the result.

Example 37. Generate JWT with specified payload and header signed with key secretKey using HS256 algorithm and save result to scenario variable JWT
Given I initialize scenario variable `header` with value `{"typ":"JWT","alg":"HS256"}`
Given I initialize scenario variable `payload` with value `{"sub":"1234567890","name":"John Doe","admin":true,"jti":"c6859320-9fb3-4784-8c2f-1ab37044acfc","iat":#{toEpochSecond(#{generateDate(P, yyyy-MM-dd'T'HH:mm:ss)})},"exp":#{toEpochSecond(#{generateDate(P1D, yyyy-MM-dd'T'HH:mm:ss)})}}`
When I generate JWT with header `${header}` and payload `${payload}` signed with key `secretKey` using HS256 algorithm and save result to scenario variable `JWT`

Tips & Tricks

Validate HTTP response body

In order to validate the body of the latest HTTP response use the response dynamic variable to access the body data in conjunction with any step responsible for data validation like data comparison, JSON, XML and other steps.

Example 38. Validate response body
When I execute HTTP GET request for resource with URL `https://httpbin.org/json`
Then JSON element from `${response}` by JSON path `$.slideshow` is equal to `
{
  "author": "Yours Truly",
  "date": "date of publication",
  "slides": [
    {
      "title": "Wake up to WonderWidgets!",
      "type": "all"
    },
    {
      "items": [
        "Why <em>WonderWidgets</em> are great",
        "Who <em>buys</em> WonderWidgets"
      ],
      "title": "Overview",
      "type": "all"
    }
  ],
  "title": "Sample Slide Show"
}
`

Save HTTP response body into variable

The HTTP response body can be saved into static variable by using the init variable step in conjunction with the response dynamic variable, it might be useful if you want to preserve the data for further computations since each subsequent HTTP call rewrites previously received response data.

Example 39. Save response body into variable
When I execute HTTP GET request for resource with URL `https://httpbin.org/json`
Given I initialize scenario variable `json` with value `${response}`