Table of contents
1.
Introduction
2.
About Rest Assured
2.1.
Benefits of Rest Assured
3.
Content Type in Rest Assured
3.1.
Importance of Content Type 
4.
Setting Content Type 
4.1.
Header Syntax 
4.2.
Implementation as Header
4.2.1.
Output
4.2.2.
Explanation
4.3.
Class Syntax
4.4.
Implementation as Class
4.4.1.
Output
4.4.2.
Explanation
5.
Retrieving Content Type
5.1.
String ContentType
5.1.1.
Input 
5.1.2.
Output
5.2.
String GetcontentType
5.2.1.
Input 
5.2.2.
Output
6.
Asserting Content Type
6.1.
Implementation 
6.1.1.
Explanation
7.
Frequently Asked Questions
7.1.
What is REST API Testing?
7.2.
What is JSON?
7.3.
Are REST assured and REST API the same?
7.4.
Why is JSON used over XML?
7.5.
Which is better, postman or rest assured?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

How to Set, Retrieve and Assert Content-Type for Request in Rest Assured

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hello ninja, 
Whenever we go to a place with a different native language than ours, we often need to communicate the language type with a person before talking. A content type is similar to this language type.

How to Set, Retrieve and Assert Content-Type for Request in Rest Assured

To set the format type of a payload we need to set the content type for request in Rest Assured. We will learn how to set, retrieve and assert content type for requests in Rest Assured.

About Rest Assured

REST Assured is an API testing tool. Johan Haleby developed it. 

About Rest Assured

REST Assured is an open-source Java package we can install in our java project, implement the API testing, validate the response we are getting, and make changes according to the response. It uses the Groovy language. 

To use REST assured in your project, you must add the dependencies below. 

<dependencies>
  <dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <version>latest version</version>
      <scope>test</scope>
  </dependency>
  </dependencies>

Benefits of Rest Assured

Some of the benefits of using REST Assured include:

  • Supports HTTP methods like GET, PUT, POST, PATCH, DELETE, etc. 
     
  • Uses Hamcrest Matchers that enable you to write checks in human-readable language.
     
  • It supports a GWT (Given/When/Then) notation for testing. This instantly makes your tests human-readable.
     
  • Since REST Assured is a Java library, it’s effortless to integrate it into a continuous integration delivery. Especially with frameworks such as JUnit or TestNG.

Content Type in Rest Assured

If you are familiar with Rest Assured, you will quickly grab these concepts. If rest assured is new to you, refer to Write First REST Assured Test to understand some basics. 
Sometimes google translate is unable to detect the correct language. You must have written the language to be translated in that case.

Content Type in Rest Assured

The content type is similar to this example. You set the content type for request in Rest Assured as a header to indicate the type of payload transmitted. 
The capacity of data to be transmitted is called payload.

Importance of Content Type 

Specifying the content type of the data transmitted is required. It is because our transmission data can be of any type. It could be JSONXML etc. The content type is specified to let Rest Assured know which format of data transmission we are using. 
We set the content type for requests in Rest Assured and response. Both formats can be different. 

Setting Content Type 

We need to explicitly set the content type for request in Rest Assured. Two methods that we use to set the content type are:

  • Method 1: Set the content type for request in Rest Assured as a key-value pair.      

Header Syntax 

The below syntax shows how to set the content type for request in Rest Assured by creating a key-value pair of content type and the format. This is passed as a header.

("Content-Type", "<type>") 

Set the content type for request in Rest Assured as a key-value pair.     

Implementation as Header

package RestAssuredBasicConcepts;
 
import org.testng.annotations.Test;
import io.restassured.RestAssured;

// Create a class 
public class SetContentType {

	@Test
	public void settingAsHeader()
		{
			RestAssured
			.given()
			.log()
			.all()

			//Key-value pair of content type and format type 
			.header("Content-Type", "application/json")

			//Example of a small payload(data to be transmitted)
			.body  ("{\r\n" +
					"    \"firstname\" : \"Anchita\",\r\n" +
					"    \"lastname\" : \"Sharma\",\r\n" +
					"    \"totalprice\" : 300,\r\n" +
					"    \"depositpaid\" : yes,\r\n" +
					"    \"bookingdates\" : {\r\n" +
					"        \"checkin\" : \"2022-12-09\",\r\n" +
					"        \"checkout\" : \"2022-12-21\"\r\n" +
					"    },\r\n" +
					"    \"complimentary\" : \"Breakfast\"\r\n" +
					"}")
			.post("https://restful-booker.herokuapp.com/booking")
			.then()
			.log()
			.all();
	}
}

Output

Output

Output

Explanation

As you can observe, we have set the content type for request in Rest Assured in a key-value pair format as ("Content-Type", "<application/Json>"). In this method, you need to make sure you spell the format type name correctly. Any mistake will cause failure.
 

  • Method 2: Set the content type for request in Rest Assured as content type.
     

In this method, we use the request specification class. This class enables us to use content type as a garbage value to specify the format type of payload. 

Class Syntax

The below syntax shows how to set the content type for request in Rest Assured by creating a garbage value of content type which will store the format type. This is passed as a class.

contentType(ContentType contentType) 
Set the content type for request in Rest Assured as content type.

Implementation as Class

package RestAssuredBasicConcepts;
 
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;

//Create a class  
public class SetContentType{

	@Test
	public void settingAsClassInstance()
	{
		RestAssured
		.given()
		.log()
		.all()
		
		//Content type as a class instance with garbage value as format type 
		.contentType(ContentType.JSON)

		//Example of a small payload(data to be transmitted)
		.body  ("{\r\n" +
				"    \"firstname\" : \"Anchita\",\r\n" +
				"    \"lastname\" : \"Sharma\",\r\n" +
				"    \"totalprice\" : 300,\r\n" +
				"    \"depositpaid\" : yes,\r\n" +
				"    \"bookingdates\" : {\r\n" +
				"        \"checkin\" : \"2022-12-09\",\r\n" +
				"        \"checkout\" : \"2022-12-21\"\r\n" +
				"    },\r\n" +
				"    \"complimentary\" : \"Breakfast\"\r\n" +
				"}")
		.post("https://restful-booker.herokuapp.com/booking")
		.then()
		.log()
		.all();
	}
}

Output

Output

Output

Explanation

As you can observe, we have set the content type for request in Rest Assured in a class format as contentType(Content-Type. JSON). Here, we have used JSON as the content type garbage value, as seen in the syntax. In this method, you can avoid mis-spelling. It works as classes work in any object-oriented programming language. 

Retrieving Content Type

When we hit any API request, we always receive a response from the server. This response is in a certain format. The correct response format should be known to retrieve and store this response for our use properly. Thus we retrieve the content type of response. 

Retrieving Content Type

We use the response interface to store the API response. We will use the same interface to retrieve the content type of response in Rest Assured.
There are two methods by which you can retrieve the content type of response. 

  • String contentType()
     
  • String getContentType()
     

We will learn about these methods in detail.

String ContentType

In this method, we retrieve the content type of the response of the string type. We will first retrieve the content type of response and then get the format type printed. This will give the result as the format type if it is present. If the content type is absent, then it returns NULL.
Look into the below example for a better understanding.

Input 

package RestAssuredBasicConcepts;
 
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
 
	public class RetrieveByStringContentType {

	@Test
	public void retrieveByStringContentType()
	{
		Response response = RestAssured
		.given()
		.contentType(ContentType.JSON)
		.body  ("{\r\n" +
				"    \"firstname\" : \"Anchita\",\r\n" +
				"    \"lastname\" : \"Sharma\",\r\n" +
				"    \"totalprice\" : 300,\r\n" +
				"    \"depositpaid\" : yes,\r\n" +
				"    \"bookingdates\" : {\r\n" +
				"        \"checkin\" : \"2022-12-09\",\r\n" +
				"        \"checkout\" : \"2022-12-21\"\r\n" +
				"    },\r\n" +
				"    \"complimentary\" : \"Breakfast\"\r\n" +
				"}")
		.post("https://restful-booker.herokuapp.com/booking");

		// Retrieve the content type 
		String contentType = response.getContentType();
		System.out.println("Content-Type of response is : "+contentType);
	}
}

Output

Output

 

String GetcontentType

In this method, we retrieve the content type of the response of the string type. We will first retrieve the content type of response and then get the format type printed. This will give the result as the format type if it is present. If the content type is absent, then it returns NULL. Both methods to retrieve the content type work the same way. They only differ by their names. 

Look into the below example for a better understanding.

Input 

package RestAssuredBasicConcepts;
 
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
 
	public class RetrieveByGetContentType {

	@Test
	public void retrieveByGetContentType()
	{
		Response response = RestAssured
		.given()
		.contentType(ContentType.JSON)
		.body  ("{\r\n" +
				"    \"firstname\" : \"Anchita\",\r\n" +
				"    \"lastname\" : \"Sharma\",\r\n" +
				"    \"totalprice\" : 300,\r\n" +
				"    \"depositpaid\" : yes,\r\n" +
				"    \"bookingdates\" : {\r\n" +
				"        \"checkin\" : \"2022-12-09\",\r\n" +
				"        \"checkout\" : \"2022-12-21\"\r\n" +
				"    },\r\n" +
				"    \"complimentary\" : \"Breakfast\"\r\n" +
				"}")
		.post("https://restful-booker.herokuapp.com/booking");

		// Retrieve the content type
		String contentType = response.getHeader("Content-Type");
		System.out.println("Content-Type of response is : "+contentType);
	}
}

Output

Output

Asserting Content Type

We assert the content type to make sure the response and request formats stay in the same format throughout execution.  It is not necessary to assert the content type. It depends on your project if you need to assert the content type.

There are three ways to assert the content type in Rest Assured.

  • TestNG method.
     
  • String method.
     
  • Direct method.
     

In TestNG and String methods, we extract and then assert the content type. We can directly assert the content type without extracting it in the direct method.
Thus, it is preferred to use the direct method. We use the ValidatableResponseOptions interface to assert the content type. Look at the example given below.

Implementation 

@Test
public void DirectAssertContentType()
{
	RestAssured
	.given()
	.contentType(ContentType.JSON)
	.body  ("{\r\n" +
			"    \"firstname\" : \"Anchita\",\r\n" +
			"    \"lastname\" : \"Sharma\",\r\n" +
			"    \"totalprice\" : 300,\r\n" +
			"    \"depositpaid\" : yes,\r\n" +
			"    \"bookingdates\" : {\r\n" +
			"        \"checkin\" : \"2022-12-09\",\r\n" +
			"        \"checkout\" : \"2022-12-21\"\r\n" +
			"    },\r\n" +
			"    \"complimentary\" : \"Breakfast\"\r\n" +
			"}")
	.post("https://restful-booker.herokuapp.com/booking")
	.then()
	.contentType(ContentType.JSON);
}

Explanation

You can observe we have used the content type () with the ValidatableResponseOptions method to assert the content type. 

Now it’s time to discuss some FAQs.

Frequently Asked Questions

What is REST API Testing?

An open-source method for testing RESTful APIs for web applications is called REST API testing. It is mainly used to test web applications that use JSON and XML. All procedures are compatible, including GET, PUT, POST, PATCH, and DELETE. In Java, the REST API is a library.

What is JSON?

JSON is a free and open-source file format and data exchange format that uses text humans can read to store and send data objects made up of arrays and attribute-value pairs.

Are REST assured and REST API the same?

A Java library called REST Assured is used to test RESTful APIs. It is frequently used to test web applications that handle JSON and XML. Additionally, it supports all RESTful methods, including PUT, GET, PATCH, POST, and DELETE.

Why is JSON used over XML?

JSON is designed for data interchange. Thus it is faster than XML. Moreover, JSON can be parsed by a javascript function. At the same time, XML requires an XML parser.

Which is better, postman or rest assured?

Rest assured is better than the postman. Rest assured, you can reuse code as it is a Java client. Moreover, in postman, we can provide only one data file for each collection, unlike rest assured.

Conclusion

This article discussed what content type is and the importance of content type. We also learned how to set the content type for request in Rest assured. We also learned how to retrieve the content type and assert the content type.
To learn more about REST assured, refer to

Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also,  refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.

Happy Learning!

Live masterclass