REST Assured Tutorial With Examples

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.

     

  2. json-web-service-api-endpoints
  3. 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.
  4. 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 = "https://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 Responsen" + 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 Responsen" + 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("https://localhost:8080/My-Jersey-Project/rest/emp/getEmp");
		System.out.println("POST Responsen" + 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("https://localhost:8080/My-Jersey-Project/rest/emp/getEmp");
		System.out.println("POST Error Responsen" + 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.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: