REST Assured Tutorial

Filed Under: Java

REST Assured is a Java Domain Specific Language API for simplifying testing of RESTful web services. REST Assured API can be used to invoke REST web services and match response content to test them.

REST Assured

REST Assured can be used to test XML as well as JSON based web services. REST Assured can be integrated with JUnit and TestNG frameworks for writing test cases for our application.

REST Assured supports POST, GET, PUT, DELETE, OPTIONS, PATCH, and HEAD requests and can be used to validate and verify the response of these requests.

REST Assured is implemented in Groovy and uses the builder pattern to create requests, set headers, parse the response and then match them with expected data. It uses Hamcrest Matchers for comparing actual response with the expected response.

One of the powerful features of REST assured is the support of XML Path and JSON Path syntax to check specific elements of the response data. It’s very similar to using XPath API.

REST Assured Tutorial Prerequisites

Before we create our REST Assured tests, we need some web services to test. Below are the additional components used in this tutorial.

  1. JSON Server: It’s a great tool to create mock JSON based web services, all it requires is a sample JSON file. It automatically creates GET, POST, PUT, DELETE API endpoints for us. I have written about it at JSON Server tutorial. Below JSON is the input for our example JSON based web service.
    
    {
      "employees": [
        {
          "id": 1,
          "name": "Pankaj",
          "salary": "10000"
        },
        {
          "name": "David",
          "salary": "5000",
          "id": 2
        }
      ]
    }
    

    Below image shows the APIs exposed by json-server mock web service.

    JSON REST Web Service API Endpoints

  2. Jersey: I am using XML based web service created in Jersey Tutorial. You can download this project from our GitHub Repository and run on tomcat.
  3. TestNG: I will use TestNG to create test cases with REST Assured, you can use JUnit too. You can learn about TestNG framework through our TestNG Tutorials.

REST Assured Tutorial

Create a maven based project in Eclipse and add Rest Assured and TestNG dependencies.


<dependency>
	<groupId>io.rest-assured</groupId>
	<artifactId>rest-assured</artifactId>
	<version>3.1.0</version>
	<scope>test</scope>
</dependency>
<dependency>
	<groupId>org.testng</groupId>
	<artifactId>testng</artifactId>
	<version>6.14.3</version>
	<scope>test</scope>
</dependency>

REST Assured GET Test

Below code snippet shows how to call GET method and test response JSON elements. Notice the use of static imports, some of them will be used in subsequent examples.


import static io.restassured.RestAssured.delete;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.hasItems;

import org.hamcrest.Matchers;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import io.restassured.http.ContentType;
import io.restassured.response.Response;

public class RESTAssuredJSONTests {

final static String ROOT_URI = "http://localhost:7000/employees";

@Test
public void simple_get_test() {
	Response response = get(ROOT_URI + "/list");
	System.out.println(response.asString());

	response.then().body("id", hasItems(1, 2));
	response.then().body("name", hasItems("Pankaj"));
}
}

Here is another complex example, where we are using TestNG DataProvider with REST Assured.


@Test(dataProvider = "dpGetWithParam")
public void get_with_param(int id, String name) {
	get(ROOT_URI + "/get/" + id).then().body("name", Matchers.is(name));
}

@DataProvider
public Object[][] dpGetWithParam() {
	Object[][] testDatas = new Object[][] { 
		new Object[] { 1, "Pankaj" },
		new Object[] { 2, "David" } };
	return testDatas;
}

REST Assured POST Example

Below code snippet shows how to create JSON Request with different headers, then test the response elements.


@Test
public void post_test() {
	Response response = given().
			contentType(ContentType.JSON)
			.accept(ContentType.JSON)
			.body("{\"name\": \"Lisa\",\"salary\": \"2000\"}")
			.when()
			.post(ROOT_URI + "/create");
	System.out.println("POST Response\n" + response.asString());
	// tests
	response.then().body("id", Matchers.any(Integer.class));
	response.then().body("name", Matchers.is("Lisa"));
}

REST Assured PUT Example


@Test
public void put_test() {
	Response response = given()
			.contentType(ContentType.JSON)
			.accept(ContentType.JSON)
			.body("{\"name\": \"Lisa Tamaki\",\"salary\": \"20000\"}")
			.when()
			.put(ROOT_URI + "/update/3");
	System.out.println("PUT Response\n" + response.asString());
	// tests
	response.then().body("id", Matchers.is(3));
	response.then().body("name", Matchers.is("Lisa Tamaki"));
	response.then().body("salary", Matchers.is("20000"));
}

REST Assured DELETE Example


@Test
public void delete_test() {
	Response response = delete(ROOT_URI + "/delete/3");
	System.out.println(response.asString());
	System.out.println(response.getStatusCode());
	// check if id=3 is deleted
	response = get(ROOT_URI + "/list");
	System.out.println(response.asString());
	response.then().body("id", Matchers.not(3));
}

REST Assured XML REST Web Services Example

Below images show the output from our Jersey REST web service.

Success Case – Response Code 200

REST Assured XML Example

Error Case – Response Code 500
REST Assured XML Error Response Example

Here is our test class showing how to test both the cases using REST Assured.


package com.journaldev.restassured;

import static io.restassured.RestAssured.given;

import org.hamcrest.Matchers;
import org.testng.Assert;
import org.testng.annotations.Test;

import io.restassured.http.ContentType;
import io.restassured.response.Response;

public class RESTAssuredXMLTests {


	@Test
	public void post_xml_test() {
		Response response = given().
				contentType(ContentType.XML)
				.accept(ContentType.XML)
				.body("<empRequest>\n" + 
						"	<id>1</id>\n" + 
						"	<name>PK</name>\n" + 
						"</empRequest>")
				.when()
				.post("http://localhost:8080/My-Jersey-Project/rest/emp/getEmp");
		System.out.println("POST Response\n" + response.asString());
		// tests
		Assert.assertEquals(response.getStatusCode(),200);
		response.then().body("empResponse.id", Matchers.is("1"));
		response.then().body("empResponse.name", Matchers.is("PK"));
	}
	
	@Test
	public void post_xml_error_test() {
		Response response = given().
				contentType(ContentType.XML)
				.accept(ContentType.XML)
				.body("<empRequest>\n" + 
						"	<id>2</id>\n" + 
						"	<name>PK</name>\n" + 
						"</empRequest>")
				.when()
				.post("http://localhost:8080/My-Jersey-Project/rest/emp/getEmp");
		System.out.println("POST Error Response\n" + response.asString());
		// tests
		response.then().body("errorResponse.errorId", Matchers.is("2"));
		response.then().body("errorResponse.errorCode", Matchers.is("Wrong ID"));
		Assert.assertEquals(response.getStatusCode(),500);
	}

}

We get the following output when above test class is executed.


POST Error Response
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><errorResponse><errorCode>Wrong ID</errorCode><errorId>2</errorId></errorResponse>
POST Response
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><empResponse><id>1</id><name>PK</name></empResponse>
PASSED: post_xml_error_test
PASSED: post_xml_test

Notice that the major change is where we are setting the request body, there is no change in the way we are retrieving response elements, whether it’s JSON or XML response. This makes REST Assured powerful and easy to learn and use.

Summary

REST Assured helps us in testing our REST APIs easily. It integrates seamlessly with TestNG and JUnit. JSON Path and XML Path allows us to easily parse the response data and test specific elements. Since it uses Hamcrest API, there are many options to match actual result with expected data.

You can download the complete example project from our GitHub Repository.

Reference: Official Documentation

Comments

  1. Laxmikanth says:

    Hi Pankaj,

    Thanks for the clear explanation, but in real time for POST method i wanted POST the value inside an array. but the values are keep on changing so i wanted to read this values from excel. Can you please help me out in this.

  2. Neha Damani says:

    For PUT and POST, can we include a json file in body?

  3. Chris says:

    Good Tutorial thank you

  4. Valentino says:

    Hi Pankaj.

    The line:

    response.then().body(“empRequest.errorCode”, Matchers.is(“Wrong ID”));

    shouldn’t be:

    response.then().body(“errorResponse..errorCode”, Matchers.is(“Wrong ID”)); ?

    1. Pankaj says:

      Yes, it should be. Thanks for noticing this, I have fixed the code.

      Also, I am surprised why the test didn’t fail. Even this test code response.then().body("errorResponse1.errorCode", Matchers.is("Wrong ID")); is also getting passed.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages