Hire QA – Specialized in QA Recruitment, Technical Interviews and Testing Solutions

Write API Response In A JSON File

Category: Rest Assured

Rest Assured provides below methods to get a response as:-

  1. As byte array :- asByteArray()
  2. As input stream :- asInputStream()
  3. As string :- asString()

All the above methods output can be used to write into a JSON file.

// Create a request specification
RequestSpecification request = RestAssured.given();
	// ContentType is an ENUM.
	.contentType(ContentType.JSON)
	// Adding URI
	.baseUri("https://hireqa.co.in/auth")
	// Adding body as string
	.body(jsonString)
Response response = request	.when().post();

// Getting response as a string and writing in to a file
String responseAsString = response.asString();
// Converting in to byte array before writing
byte[] responseAsStringByte = responseAsString.getBytes();

// Creating a target file
File targetFileForString = new File("D:/RestAssured/targetFileForString.json");
// Writing into files
Files.write(responseAsStringByte, targetFileForString);

// Getting response as input stream and writing in to a file
InputStream responseAsInputStream = response.asInputStream();
// Creating a byte array with number of bytes of input stream
byte[] responseAsInputStreamByte = new byte[responseAsInputStream.available()];
// Reads number of bytes from the input stream and stores them into the byte
// array responseAsInputStreamByte.
responseAsInputStream.read(responseAsInputStreamByte);
// Creating a target file
File targetFileForInputStream = new File(D:/RestAssured/targetFileForInputStream.json");
// Writing into files
Files.write(responseAsInputStreamByte, targetFileForInputStream);

// Directly getting a byte array
byte[] responseAsByteArray = response.asByteArray();
// Creating a target file
File targetFileForByteArray = new File("D:/RestAssured/targetFileForByteArray.json");
// Writing into files
Files.write(responseAsByteArray, targetFileForByteArray);

Leave a Reply

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