Rest Assured Questions
Parsing JSON File Using JSON Path and Query
String payload="path of json file";
String jsonstring ="";
try{
jsonstring= new String(Files.readAllBytes(Paths.get(payload));
}catch(IOException E){}
Object dataobject=Jsonpath.parse(jsonstring).read("$.['data'].[?(@id==2)].email");
System.out.println(dataobject.toString())
Parsing JSON response from get request Using JSON Path and Query
RestAssured.baseURI="https://reqres.in/api";
Response resp=given().when().get("/users").then().extract().response();
Object dataobject=Jsonpath.parse(resp.asString()).read("$.['data'].[?(@id==2)].email");
System.out.println(dataobject.toString())
Getting response of an getrequest without using rest assured i.e using simple java?
URL url = new URL("https://reqres.in/api/users");
HttpsURLConnection connection= (HttpsURLConnection)url.openConnection();
connection.setRequestMethod('GET");
System.out.println(connection.getResponseMessage());
StrngBuilder sb = new StringBuilder();
Scanner scan = new Scanner(connection.getInputStream());
while(scan.hasNext())
{
sb.append(scan.nextLine());
}
1. What is REST?
- REST (Representational State Transfer) is an architectural style for developing web services which exploit the ubiquity of HTTP protocol and uses HTTP method to define actions. It revolves around resource where every component being a resource that can be accessed through a shared interface using standard HTTP methods.
- In REST architecture, REST Server provides access to resources and client accesses and makes these resources available.
- Each resource is identified by URIs or global IDs, and REST uses multiple ways to represent a resource, such as text, JSON, and XML.
2. What are main differences between API and Web Service?
- All Web services are APIs but not all APIs are Web services.
- Web service uses three styles of use: SOAP, REST and XML-RPC for communication whereas API may be exposed in multiple ways.
- Web service needs a network to operate but APIs don’t need a network to operate.
3. Automate GET method and validate status code?
@Test(description="Verify status code for GET method-users/2 as 200")
public static void verifyStatusCodeGET() {
Response resp=given().when().get("https://reqres.in/api/users/2");
assertEquals(resp.getStatusCode(),200);
}
4. Automate GET method and fetch response body?
@Test(description="Verify status code for GET method-users/2 as 200")
public static void verifyStatusCodeGET() {
Response resp=given().when().get("https://reqres.in/api/users/2");
assertEquals(resp.getBody().asString(),200);
}
5. Automate GET method and verify value from response body?(validate that total number pages =12)
@Test(description="Verify status code for GET method-users/2 as 200")
public static void verifyStatusCodeGET() {
Response resp=given().when().get("https://reqres.in/api/users");
System.out.println(resp.path("total").toString());
assertEquals(resp.getStatusCode(),200);
assertEquals(resp.path("total").toString(),"12");
6. What are the types of Status codes?
1xx informational response – the request was received, continuing process
2xx successful – the request was successfully received, understood, and accepted
3xx redirection – further action needs to be taken in order to complete the request
4xx client error – the request contains bad syntax or cannot be fulfilled
5xx server error – the server failed to fulfil an apparently valid request
7. How to pass query param with GET method in Rest Assured?
@Test
public void validateQueryParamInGiven() {
Response resp = given().queryParam("page", "2").
when().get("https://reqres.in/api/users");
assertEquals(resp.getStatusCode(),200);
System.out.println(resp.getBody().asString());
}
8. How to pass header for GET method in Rest Assured?
@Test
public void validateGivenHeader() {
Response resp = given().header("Content-Type", "application/json").
when().get("https://gorest.co.in/public-api/users");
assertEquals(resp.getStatusCode(),200);
System.out.println(resp.getBody().asString());
}
9. How to automate PUT method in Rest Assured?
@Test(description="validate with jsonpath and json object and pass post body as json file")
public void MethodValidationPUT() throws IOException, ParseException {
FileInputStream file = new FileInputStream(new File (System.getProperty("user.dir")+"\\Data\\putmehtod.json"));
Response resp =
given().header("Content-Type" , "application/json").body(IOUtils.toString(file,"UTF-8")).
when().put("https://reqres.in/api/users/2");
assertEquals(resp.getStatusCode(),200);
assertEquals(resp.path("job"),"testing");
}
10. How to automate POST method in Rest Assured?
@Test(description="validate with jsonpath and json object and pass post body as json file")
public void MethodValidationPOST() throws IOException, ParseException {
FileInputStream file = new FileInputStream(new File (System.getProperty("user.dir")+"\\Data\\putmehtod.json"));
Response resp =
given().header("Content-Type" , "application/json").body(IOUtils.toString(file,"UTF-8")).
when().post("https://reqres.in/api/users");
assertEquals(resp.getStatusCode(),201);
assertEquals(resp.path("job"),"testing");
}
11. How to use Basic authentication in automation?
Response resp = given()
.auth()
.basic("sid", "sid").when().get("https://reqres.in/api/users/2");
12. How to use Pre-emptive authentication in automation?
Response resp1 = given()
.auth()
.preemptive().basic("sid", "sid").when().get("https://reqres.in/api/users/2");
13. How to use digest authentication in automation?
Response resp2 = given()
.auth()
.digest("sid", "sid").when().get("https://reqres.in/api/users/2");
14. How to use Oauth2 authentication in automation?
Response resp3 = given()
.auth()
.oauth2("").when().get("https://reqres.in/api/users/2");
15. How to use Oauth authentication in automation?
Response resp4 = given()
.auth()
.oauth("consumerKey", "consumerSecret", "accessToken", "secretToken").when().get("https://reqres.in/api/users/2");
16. How to use header for authorization(oauth2) in automation?
Response resp5 = given().header("Authorization","accessToken")
.when().get("https://reqres.in/api/users/2");
}
17. How to Update/add the Json values dynamically?
@Test(testName = "Add a pet to store", priority = 1,enabled = true)
public void addPet() throws ParseException, FileNotFoundException, IOException {
String endpoint = URL.getEndPoint("/pet");
String payload = PayloadConverter.generateString("Swagger_petstore.json");
//Using Jayway json path library. Add maven dependency
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.7.0</version>
</dependency>
Configuration configuration = Configuration
.builder()
.options(Option.SUPPRESS_EXCEPTIONS)
.build();
// File json = new File(System.getProperty("usre.dir")+"\\resources\\Swagger_petstore.json");
// System.out.println(json.getAbsolutePath());
DocumentContext parsed = JsonPath.using(configuration).parse(payload);
parsed.set("$.id", "56");
parsed.set("$.photoUrls[0]", "url1");//updating existing key
parsed.set("$.photoUrls[1]", "url2");
parsed.set("$.tags[0].name", "Brown");
parsed.put("$.tags[0]", "address", "man"); //adding new key
// Scenario for adding new elemnets in tags array
JsonPath pathToArray = JsonPath.compile("$.tags");
parsed.add(pathToArray, Collections.singletonMap("road", "Road1"));
parsed.add(pathToArray, Collections.singletonMap("Building", "Building1"));
String actual = parsed.jsonString();
System.out.println("Updated actual="+actual);
//Pretty printing
//1st method using faster xml jackson bind pretty print
ObjectMapper mapper = new ObjectMapper();
Object json = mapper.readValue(actual, Object.class);
String jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); // Pretty print JSON
System.out.println(jsonStr);
Response resp = RESTCalls.POSTRequest(endpoint, actual);
System.out.println("updated response="+TestUtils.getJSONResponseString(resp));
//2nd way org.json.Jsonobject for pretty print
JSONObject jo= new JSONObject(TestUtils.getJSONResponseString(resp));
System.out.println("pretty="+jo.toString(4));//4 in the tostring parameter is for pretty print
Assert.assertEquals(resp.path("id"), 110);
Assert.assertEquals(resp.jsonPath().get("tags[0].name"), "Brown");
resp.then().body("name", equalTo("lebroder1"));
resp.then().body("category.id", equalTo(11));
Assert.assertEquals(resp.jsonPath().get("name"), "lebroder1");
}
18. Json to XML?
@Test(priority = 4, enabled = false)
public void Json_Xml() throws IOException {
String path = "./resources/Swagger_petstore.json";
String jsonstring = new String(Files.readAllBytes(Paths.get(path)));
System.out.println("Json Stirng=" + jsonstring);
JSONObject json = new JSONObject(jsonstring);
System.out.println("Json to XML=" + XML.toString(json));
}
18. XML to Json ?
@Test(priority = 5 , enabled = false)
public void Xml_json() throws IOException {
String path = "./resources/Swagger_petstore.json";
String jsonstring = new String(Files.readAllBytes(Paths.get(path)));
System.out.println("Json Stirng=" + jsonstring);
JSONObject json = new JSONObject(jsonstring);
String xml=XML.toString(json);
//1st-Method
json = XML.toJSONObject(xml);
System.out.println("xml to json="+json.toString());
//2nd Method
System.out.println("xml to json2="+XML.toJSONObject(xml));
}
19. Authorization types ?
Basic and Digest , Bearer, form and Oath
Basic:
- Root node ($) denotes the root member of a JSON structure whether it is an object or array. We included usage examples in the previous subsection.
- Current node (@) represents the node being processed. We mostly use it as part of input expressions for predicates. Suppose we are dealing with book array in the above JSON document; the expression book[?(@.price == 49.99)] refers to the first book in that array.
- Wildcard (*) expresses all elements within the specified scope. For instance, book[*] indicates all nodes inside a book array.
Comments