Request and Response validation using KarateDSL

Priyanka Brahmane
7 min readJun 10, 2021

Welcome Back TestCommunity!!!

I hope this series is giving you a better understanding of KarateDSL and addressed your doubts.

Every API automation tool uses its own method for handling HTTP keywords and validating request & response. You’ll be pleasantly amazed at how well KarateDSL has simplified and implemented these concepts.

You are currently reading the fifth blog in my KarateDSL series, which focuses on request and response validations as well as HTTP keyword processing. If you missed to read any of the previous blogs in this series, here’s a link to my medium channel.

Do you want to learn more about how Karate DSL can help you validate requests and answers more effectively?

source. google image

Let’s take a deeper look at each concept individually:

API: https://jsonplaceholder.typicode.com/comments?postId=1

HTTP URL: A URL is just an identifier of a specific unique resource on the Internet. Until you use the url keyword again, a URL remains constant.

Syntax for defining URL in Gherkins language is-

Given url 'https://jsonplaceholder.typicode.com'

For appending dynamic value(s) to a URL, use the “+” concatenation operator.

And def url_path = 'comments'Given url 'https://jsonplaceholder.typicode.com/' + url_path + '?postId=1'

HTTP Path: Its sole purpose is to set the HTTP Path. “path” keyword is used for this purpose.

Example: https://jsonplaceholder.typicode.com/comments

Given url 'https://jsonplaceholder.typicode.com'And path 'comments'When method GetThen status 200

Example: http://openlibrary.org/api/volumes/brief/isbn/9780525440987.json

You may also declare many path values, it can done by reusing this keyword.

If you want to repeat the execution for the same url but various url path values, use the code below.

Examples:
https://jsonplaceholder.typicode.com/comments?postId=1
https://jsonplaceholder.typicode.com/comments1?postId=1
https://jsonplaceholder.typicode.com/comments2?postId=1

Given url 'https://jsonplaceholder.typicode.com/' + '<url_path>' + '?postId=1'When method GetThen status 200Examples:|url_path ||comments ||comments1||comments2|

HTTP Param: When the client, such as a browser, requested a specific resource from the web server using HTTP protocol, GET parameters/URL parameters/Query string are used.

Query params are usually name-value pairs, separated by an equals sign “=”.

The “param” keyword is used in the Http URL to pass a single query parameter.

Example: https://jsonplaceholder.typicode.com/comments?postId=1

Syntax for declaring param is-

Given url 'https://jsonplaceholder.typicode.com'And path 'comments'And param postId = 1When method GetThen status 200

HTTP Params: If you wish to send multiple query parameters in an HTTP URL, the keyword “params” is the right option.

Example: https://jsonplaceholder.typicode.com/comments?postId=1&id=2

Given url 'https://jsonplaceholder.typicode.com'And path 'comments'And params {postId:1,id:2}When method GetThen status 200

HTTP Request Body: The data bytes transmitted in an HTTP transaction message immediately after the headers, if any, are known as the HTTP request Body.

Method 1: Define a variable to store all key-value pairs and passed it to the “request” keyword.

Given url 'url-of-your-post-api'And def req_body = {"key1": "value1", "key2": "value2" }And request req_bodyWhen method PostThen status 200

Method 2: The request body can also be passed through a JSON file.

Given url 'url-of-your-post-api'And def RequestBody = read('my-json.json') 
And request RequestBody #Option 1
ORAnd request read('my-json.json') # Option 2 - without using def variableWhen method PostThen status 200

HTTP Method: HTTP specifies a variety of request methods for specifying the desired action for a particular resource. These request methods are commonly referred to be HTTP verbs, despite the fact that they can also be nouns.. The HTTP verb are get, post, put, delete, patch, options, head, connect, trace. HTTP verbs are not case-sensitive, it can be declared in lower/upper case.

When method get/post/put/path/delete

If you want to know more about HTTP methods refer this link.

HTTP Status: “status” is used to set the response status of triggered API. If you set expected status to 200 and API returns other status (4XX/5XX /even 2XX excluding 200) then test scenario will fail and rest of the scenario’s steps will be skipped.

Then status 200

Let’s see how Request are Handled in KarateDSL ?

Request Header: With the Post/Put HTTP method, the header is passed. We can use the “header” keyword when an API only expects one request header.

Given url 'url-of-your-post-api'And header Content-type = "application/json"And def req_body = 
"""
{
"key1": "value1",
"key2": "value2"
}
"""And request req_bodyWhen method PostThen status 200

Request Headers: When an API expects multiple request headers, in such scenario “headers” can be used.

Given url 'url-of-your-post-api'And def headerParams = { 'Content-type' : 'application/json', 'Sec-Fetch-Mode' : 'cors'}And headers headerParamsAnd def req_body = 
"""
{
"key1": "value1",
"key2": "value2"
}
"""And request req_bodyWhen method PostThen status 200

Request cookie: A cookie is a small piece of data sent by a server to a user’s web browser. It’s possible that the browser will save it and send it back with subsequent requests to the same server. It’s typically used to determine whether two requests came from the same browser — keeping a user logged in.

For passing single cookie with the Post/Put API, “cookie” keyword is used.

Given url 'url-of-your-post-api'And header Content-type = "application/json"And cookie Cookie = '_abck=4A13D586188793D40835F395CE413F23~0~YAAQBpYRYJkx2o' # Option 1 OR# Option 2- if it is passed in headerAnd header Cookie = '_abck=4A13D586188793D40835F395CE413F23~0~YAAQBpYRYJkx2o' And def req_body = 
"""
{
"key1": "value1",
"key2": "value2"
}
"""And request req_bodyWhen method PostThen status 200

Request Cookies: When using the Post/Put API, you can pass multiple cookies together by using “cookies” keyword.

Given url 'url-of-your-post-api'And header Content-type = "application/json"And cookies { firstKey: 'Value1', sencondKey: 'Value1' }And def req_body = 
"""
{
"key1": "value1",
"key2": "value2"
}
"""And request req_bodyWhen method PostThen status 200

How to handle response and its headers?

Response: To print JSON/XML response, “ response” keyword is used.

Given url 'https://jsonplaceholder.typicode.com'And path 'comments'And params {postId:1,id:2}When method GetThen status 200And print response

Response Headers: are used to provide detailed information about the response.

Sample Response headers:

The “ responseHeaders” keyword in KarateDSL provides a way to acquire all response headers. You can print a list of all response headers using this keyword if you want to see them all at once.

Given url 'https://jsonplaceholder.typicode.com'And path 'comments'And params {postId:1,id:2}When method GetThen status 200And print responseHeaders

Pass the name of the header in square brackets-[‘header-name’] to retrieve a specific header from a response, as demonstrated in the code snippet below.

Given url 'https://jsonplaceholder.typicode.com'And path 'comments'And params {postId:1,id:2}When method GetThen status 200And print responseHeadersAnd def contentType = responseHeaders['Content-Type'][0]And print contentTypeAnd def contentType = responseHeaders['cf-request-id'][0]And print contentTypeAnd def contentType = responseHeaders['Report-To'][0]And print contentType

Response Type: The type of data in the response is revealed by responseType. This is useful when karate tries to parse the raw HTTP response body into JSON or XML. A warning is recorded if parsing fails, and the response is then returned as a plain string. It can take one of three forms: json, xml, or string.

In this scenario, validation may be required, and we can just use “responseType” keyword.

Response Time: The total amount of time it takes for a server to respond to a service request is known as response time.

The “responseTime” keyword is used to add a validation on the overall execution time, which is returned in milliseconds. You can also assert response time.

Response Cookie: The “responseCookies” keyword can be used to get the value of the cookies.

Given url 'https://jsonplaceholder.typicode.com'And path 'comments'And params {postId:1,id:2}When method GetThen status 200And print responseCookies

Now I’ll wrap up this blog, and hope the examples provided in this blog have helped you grasp the approaches for handling HTTP keywords, request and response validations. We’ll explore about different types of actions, along with response assertions and matching, in the forthcoming blog.

I’d appreciate it if you could let me know your thoughts in the comments box below, and be sure to click the Follow button to stay updated with the latest blogs. Looking forward to meet you in the upcoming blogs to explore more concepts of KarateDSL. You may also connect with me on LinkedIn.

Until then, stay safe and enjoy learning!!!

--

--

Priyanka Brahmane

AM SDET Automation @M&G | QA Lead @ MyGlamm | QA Automation engineer @ Ex-Paytm Insider| Ex-Automation Tester @ Reliance Jio Infocomm Ltd. | Ex-Software Develop