Writing API Response to Json File using Rest Assured
During API Automation there be a scenario were json response has to be stored so that it can be used as a input to other API request
Or
If we want to write the REST API Response to Json File in case if the response has to be debugged
Or
If the UI Framework is integrated with Rest Assured API Framework then we can make the rest call once and store the response in JSON file so that it can be used against UI Validation
Required Dependencies
Here i have used Rest Assured
1 2 3 4 5 6 7 |
<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured --> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>4.4.0</version> <scope>test</scope> </dependency> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package jsonutilities; import java.io.File; import java.io.IOException; import com.google.common.io.Files; import io.restassured.http.ContentType; import io.restassured.response.Response; import static io.restassured.RestAssured.given; public class ResponseToJsonFile { public static void main(String[] args) throws IOException { // Create a GET Request Response response = given() .contentType(ContentType.JSON) .when() .get("https://restful-booker.herokuapp.com/booking") .then() .extract().response(); // Get the Byte Array byte[] responseAsByteArray = response.asByteArray(); // Create a target file File targetFileForByteArray = new File("src/main/resources/targetFileForByteArray.json"); // Writing into files Files.write(responseAsByteArray, targetFileForByteArray); System.out.println("JSON File Created"); } } |