File Downloads
In this lesson, we will look at how to download the response to a file using the Rest Assured library.
We'll cover the following...
What is file download?
There are instances where we need to save the response body message as a file. In this example, we will make a GET
request that returns a JSON
string which will be saved as a file.
Example: Download JSON file
- HTTP method: GET
- Target URL:
http://ezifyautomationlabs.com:6565
- Resource path:
/educative-rest/students
Take a look at the code below:
Press + to interact
import static org.testng.Assert.assertEquals;import static org.testng.Assert.assertTrue;import java.io.File;import java.io.IOException;import java.nio.file.Files;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.testng.annotations.Test;import io.restassured.RestAssured;import io.restassured.response.Response;public class APIDemo {private static final Logger LOG = LoggerFactory.getLogger(APIDemo.class);@Testpublic void testDownload() throws IOException {String url = "http://ezifyautomationlabs.com:6565/educative-rest/students";// making API callResponse response = RestAssured.given().log().all(true).get(url).andReturn();// validating http status codeassertEquals(response.getStatusCode(), 200, "http status code");// reading the response boody as byte[]byte[] bytes = response.getBody().asByteArray();// validating that the response content length > 0assertTrue(bytes.length > 0, "response content length is 0");// writing the byte[] to fileFile file = new File("students.json");Files.write(file.toPath(), bytes);// validating the existence and size of fileassertTrue(file.exists(), "file " + file + " does not exist");assertTrue(file.length() > 0, "file size is 0");assertEquals(bytes.length, file.length(), "file size and response content");String content = new String(Files.readAllBytes(file.toPath()));LOG.info("printing content of the file => {}", content);}}
The output of this code returns the following response:
[{
...