Skip to content

Rest Assured

REST Assured is a Java library for validation of REST web services.

Benefits of REST Assured

  1. REST Assured reduces the need for writing same section of code many times, which is required to set up an HTTP connection, send a request and receive and parse a response.

  2. It supports for BDD (Behavior-Driven Development) by using test notation, Given, When and Then, which makes the tests human readable.

  3. It provides interesting features such as,

a. Measuring Response Time

b. Validate Response Time

c. JSON Response Verification, etc

Configure rest-assured

In the pom.xml file add the rest assured dependency for maven

1
2
3
4
5
6
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>4.1.2</version>
    <scope>test</scope>
</dependency>

Few interesting features of REST Assured

BDD supported syntax

REST Assured provides BDD (Behavior Driven Development) supported format. It helps to write cleaner test codes which are human readable. In the request the pre-conditions are listed under the “Given” section. The action to perform is given under the “When” section. Finally, the verification is given under “Then” section

restassured

Handling parameters

Path Parameters

1
2
3
4
5
6
@Test
public void pathParamTest() {
given().pathParam("user", "user1")
.when().get(" http://demoapplication/profile/{user}")
.then().statusCode(200);
}

Query Parameters

1
2
3
4
5
@Test
public void queryParamTest() {
given().queryParam("name", "user1").when().get(" http://demoapplication/profile")
.then().statusCode(200);
}

Form Parameters

To send form parameter with the POST call

1
2
3
4
5
6
7
8
@Test
public void formParamTest () {
given().contentType("application/x-www-form-urlencoded; charset")
.formParam("username", “Test User”)
.formParam("password", “Test123&&”)
.when().post(“http://demoapplication/login”)
.then().statusCode(200);
}

Validate the status code

Let’s assume that we have to validate whether the status code is 200. You can simply achieve that

1
2
3
4
5
@Test
public void validateStatusCode() {
given(). when()
.get(“http://demoapplication/statuscheck”).then().statusCode(200);
}

Get the response time

If we have to measure the response time, we can achieve that using following code segment. You can get the response time in a specific time unit as desired.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@Test
public void MeasureResponceTimeInMiliSeconds() {
long timeinMilliseconds =  given()
.when()
.get(“http://demoapplication/statuscheck”).timeIn(MILLISECONDS);
System.out.println("Responce time in miliseconds is" + timeinMilliseconds);
}
@Test
public void messureResponceTimeInNanoSeconds() {
long timeinNanoSeconds = given().when().get(“http://demoapplication/statuscheck”).timeIn(NANOSECONDS);
System.out.println("Responce time in nano seconds is" + timeinNanoSeconds);
}

Validate the Response time

There can be situations where you want to validate the response time. You can simply validate whether the response time is below a predefined value using following method

1
2
3
4
5
6
@Test
public void validateResponceTime() {
given()
.when()
.get(“http://demoapplication/statuscheck”).then().time(lessThan(1000L), MILLISECONDS);
}

JSON response validation

Please refer the following JSON response

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
{  
   "mystore":{  
      "book":[  
         {  
            "author":"Dan Brown",
            "category":"fiction",
            "price":590,
            "name":"Angels & Demons"
         },
         {  
            "author":"Carolyn Keene",
            "category":"mystery",
            "price":420,
            "name":"Nancy Drew : The Secret of the Old Clock"
         }
         {  
            "author":"J. R. R. Tolkien",
            "category":"fiction",
            "isbn":"0-395-19395-8",
            "price":650,
            "name":"The Lord of the Rings"
         },
         {  
            "author":"Meg Cabot",
            "category":"young adult novels",
            "isbn":"0-553-21311-3",
            "price":560,
            "name":"The Princess Diaries"
         }
                ]
   }
}

1.Assume you are to validate whether the response contains all the books

1
2
3
4
5
6
7
8
@Test
 public void validateBooks() {
 given()
.when()
.get(“http://demoapplication/bookstore”)
.then()
.body("mystore.book.name",hasItems("Angels & Demons", "The Lord of the Rings", "The Princess Diaries","Nancy Drew : The Secret of the Old Clock"));
}

2. Assume you are to validate that the names of the books with a price greater than 500 correct

1
2
3
4
5
6
7
8
9
@Test
public void validateJason() {
given()
.when()
.get(“http://demoapplication/bookstore”)
.then()
.body( "mystore.book.findAll { it.price > 500 }.name",
hasItems("Angels & Demons", "The Lord of the Rings", "The Princess Diaries"));
}

Extract response data

WE can do that in two ways

1.Using built in REST Assured functionalities

2.Using JSON path

Using built in REST Assured functionalities

1.To extract the whole response as string

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@Test
 public void extractValues(){
Response response =  given()
.when()
.get(“http://demoapplication/bookstore”)
.then()
  .contentType(ContentType.JSON)
  .extract().response();
  System.out.println ("Here comes the response" + response.asString ());
}
  1. To extract a specific value, you can use the following code. Let’s assume that you are to extract the author of the first book

```` @Test public void extractSpecificValues(){ String author = given() .when() .get(“http://demoapplication/bookstore”) .then() .contentType(ContentType.JSON).extract(). path("mystore.book.author[0]"); System.out.println ("Here comes the Auther of the first book" + author); }

1
3. To extract a multiple value, you can use the following code. Let’s assume that you are to extract the author of the first book, author of the second book and the Name of the third book.

@Test public void extractMultipleValues(){ Response response = given() .when() .get(“http://demoapplication/bookstore”) .then() .contentType(ContentType.JSON) .extract().response(); String firstAuthor= response.path("mystore.book.author[0]"); String secondAuthor= response.path("mystore.book.author[1]"); String thirdBookName= response.path("mystore.book.name[2]"); System.out.println ("Author of the first book is " + firstAuthor); System.out.println ("Author of the second book is " + secondAuthor); System.out.println ("Name of the third book is " + thirdBookName); } ```

Using JSON path

In order to use json-path functionalities you need to include the json-path maven dependency in the pom.xml file. The latest json-path maven dependency as of now

1
2
3
4
5
6
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
<scope>test</scope>
</dependency>

1.Let’s assume that you are to extract the categories of the books.

``` @Test public void extractValueswithJsonPath (){ Response response = given() .when() .get(“http://demoapplication/bookstore”).andReturn(). then().contentType(ContentType.JSON).extract().response();

List categories = response.jsonPath().getList("mystore.book.category"); System.out.println("Categories of the books are " + Arrays.toString(categories.toArray()));

} ```