Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
REST Assured
3.
Writing Response in a Text File
4.
Code
5.
Output
6.
Explanation
7.
Frequently Asked Questions
7.1.
How do you pass JSON payload in Rest assured?
7.2.
Where is REST assured used?
7.3.
What is the difference between PATCH, PUT and POST in Rest assured?
7.4.
Can we delete a resource using the POST method?
7.5.
Why is Maven used in projects?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

REST Assured – Writing Response in a Text File

Author Kanak Rana
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Hello Ninjas! Welcome to this blog, where we discuss Rest Assured – Writing Response in a Text File.

REST Assured – Writing Response in a Text File

Here in this article, we have covered the definitions of REST assured, know about writing a response in a text file with the help of code, and later explanation is given to understand what is happening in the code. 

Let's start our topic, and REST Assured – Writing Response in a Text File, by first knowing about REST Assured.

REST Assured

Rest Assured is a Java library that allows you to test and validate REST(Representational State Transfer) services, APIs(application program interface), and Web Services.

Previously, API testing was more complex than with Ruby and Groovy. It provides that simplicity and flexibility in Java.

REST Assured

It is a platform that is open source. It is based on HTTP Builder and can handle POST, GET, PUT, DELETE, OPTIONS, PATCH, and HEAD requests.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Writing Response in a Text File

Testing and validating REST resources in any application, especially in Java, is complex and confusing. REST Assured simplifies things by allowing us to use REST-Assured Java APIs to send requests and validate anything in the Response.

However, while performing this simple request and response, we frequently run into the problem of figuring out how to configure REST Assured logs to be written to a file or test logs rather than printed to the console.

Writing the same requests and responses to the log file will aid us in future debugging or a better understanding of our test flow.

Now, let us implement code to log the Response of the POST request (Let's Write First POST Request in REST Assured) into a text file.

Code


package javaPackageName;
 
import java.io.File;
import java.io.PrintStream;
import io.restassured.RestAssured;
import org.testng.annotations.Test;
import java.io.FileNotFoundException;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
    
 public class POSTRequest {
 @Test
       
 	public void post_request() throws FileNotFoundException
 	{
 		String jsonString = "{\"name\" : \"kanak\",\"password\" : \"kanak123\"}";
 		
 		// Construct a request specification
 		RequestSpecification request= RestAssured.given();
 		
 		// Setting content type to specify the format in which the request payload will be sent.
 		request.contentType(ContentType.JSON);
 		
 		// Adding URI
 		request.baseUri("https://reqres.in/api/users");
 		
 		// Adding body as string
 		request.body(jsonString);
 		
 		// Calling POST method on URI. After hitting, we get Response
 		Response response = request.post();
 		
 		// Printing Response as string
 		System.out.println(response.asString());
 		
 		try {
 			PrintStream out = new PrintStream(new File("src/main/resources/targetFile.txt"));
 			System.setOut(out);
 		}
 		catch(FileNotFoundException fx) 
 		{
 			System.out.println(fx);
 		}
 		
 		// Get Validatable response to perform validation
 		ValidatableResponse validatableResponse = response.then();   
 		
 		// Validate status code as 201
 		validatableResponse.statusCode(201);
 		
 		System.out.println(response.getStatusCode());
 		System.out.println(response.getTime());
 	}
}

Output

Output

Explanation

In the above code, we created a method called "post_request". Under this method, we defined a JSON string variable of string type to store JSON values. Then we constructed a request specification, set the content type, and added URI. After we added URI, we added the body as a string. Then we called the POST method on URI, printed the Response, wrote the response to a text file(targetFile.txt), and performed validation.

Frequently Asked Questions

How do you pass JSON payload in Rest assured?

First, the contents of the file should be converted to a string. Then we should read the file content and convert it to Byte data type. Once the entire data is converted to Byte, we should finally convert it to string. We shall utilize an external JSON file as a payload for executing a POST request.

Where is REST assured used?

Rest Assured is used to validate REST APIs using the Java library. The Java library acts as a headless client to interact with Rest web services. It is based on the Rest Assured library and can validate the server's HTTP responses.

What is the difference between PATCH, PUT and POST in Rest assured?

POST is always for creating a resource (it does not matter if it was duplicated), and PUT is checking if the resource exists and then updating it, or else creating a new resource. PATCH is always for updating a resource.

Can we delete a resource using the POST method?

We may use the POST method to create, update and delete resources, but this is considered an inappropriate design. The different HTTP verbs standardize modern ways of creating REST APIs.

Why is Maven used in projects?

Maven primarily assists in downloading dependencies, which are libraries or JAR files, for Java-based applications.

Conclusion

In this blog, we have learned about Rest assured – Writing Response in a Text File. We have covered the Rest assured, writing Response in a text file with java code.

For more such articles like REST Assured – Writing Response in a Text File, look at the following: 

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

Happy Coding!

Previous article
Let’s Write First DELETE Request in REST Assured
Next article
REST Assured –RequestSpecification – How the request will look like
Live masterclass