Showing posts with label API rest assured. Show all posts
Showing posts with label API rest assured. Show all posts

Wednesday, July 7, 2021

Latest top 20 API Automation Interview Questions and Answer Set 5








********************************************************************************
                                                API Important interview Questions
********************************************************************************

1 What do you understand by REST?
REST stands for Representational State Transfer. It is a web standards based architecture and take advantage of ubiquity of HTTP protocol and leverages HTTP method for data communication and to define actions.

It completely revolves around resources where every component is a resource and a resource is accessed by a common interface using HTTP standard methods.

In the architecture of REST, a REST Server provides access to resources and REST client accesses and presents the resources. Each resource in REST is identified by URIs or global IDs. It uses various representations to represent different resources like text, JSON and XML. Now a days JSON is the popular format and being commonly used in web services.


2. Explain the RESTFUL webservice?
A.2. Web services that are written by applying REST architectural concept are known as RESTFUL web services. HTTP methods are used in these services to implement the concept of REST architecture. It mainly focuses on system resources and defines how state of resource should be transported over HTTP protocol to different clients written in different language.

They usually defines a URI that provides resource representation such as JSON and set of HTTP Methods. HTTP methods like GET, POST, PUT and DELETE can be used to perform CRUD operations in RESTFUL webservices.


3. What is a Resource in REST and how to represent a Resource?
In REST architecture, every component is treated as a resource. These resources can be text files, images, videos, html pages or dynamic business data. REST Server provides access to resources and REST Client accesses and modifies those resources. Each resource in REST is identified by URIs or global IDs

Each resource in REST is identified by logical URLs or global IDs. Unlike SOAP web services, we view the product data as a resource and this resource should contain all the required information.

REST uses various representations like text, JSON and XML to represent a resource . XML and JSON are the most popular and commonly used representations of resources.


4. Mention some key characteristics of REST?
Below are some of the key characteristics of REST:
Rest is defined as stateless, hence the server has no state or no session data.
The server can be restarted between two calls as every data is passed to the server. This is possible with a well-applied REST API.
Mostly Web Services uses POST method to make operations, but REST uses GET method to access the resources.


5. What are the best practices to design a resource representation?
Below are some of the best practices that needs to be considered while designing a representation format of a resource in a RESTful web services −
Understandability: Both the Server and the Client should understand and utilize the representation format of the resource.
Completeness: The Format used should be able to represent a resource completely. It should be able to represent simple as well as complex structures of resources.
For eg., one resource can contain another resource.
Likability : One resource can have a linkage to another resource, hence a format should be able to handle such situations.


6. What are the core components of a HTTP Request?
There are 5 parts of a HTTP Request−
Verb: It indicates HTTPS methods like GET, PUT, POST, DELETE.
URI: It is Uniform Resource Identifier that is used to identify the resource on Server.
HTTP Version: It indicates the version of HTTP, for eg. HTTP v1.1
Request Header: It contains the metadata for HTTP request message like key-value pairs. For eg.: client or browser type, format supported by client, format of message body, cache settings,etc.
Request Body: It contains Message content or Resource representation.
Q.7. What are the HTTP methods that are supported by REST?


A.7. Below are the HTTP methods that are supported by REST:
GET: It is used to request a resource at the request URL. It do not contain a request body.
POST: It is used to submit information to the service for further processing. It typically returns the modified or new resource.
PUT: It is used to update the resource at the request URL.
DELETE: It is used to remove the resource at the request URL.
OPTIONS: It is used to indicate the supported techniques.
HEAD: It returns the information about the request URL.



8. What are the core components of HTTP Response?
There are 4 parts of a HTTP Response:
Status/Response Code: It indicates server status for the requested resource. For eg. Code 200 means response is ok and code 404 means resource is not found
HTTP Version: It indicates the version of HTTP, for eg. HTTP v1.1
Response Header: It contains the metadata for HTTP response message like key-value pairs. For eg.: content length, content type, response data, server type,etc.
Response Body: It contains Response Message content or Resource representation.




9. What is URI and its purpose in REST based webservices? What is the format of a URI in REST architecture?
URI stands for Uniform Resource Identifier. In REST Architecture, each resource is identified by its URI.
The main purpose of URI is to locate a resource on the server that is hosting the webservice.

The format of URI is:
<protocol>://<service-name>/<ResourceType>/<ResourceID>


10.What are the best practices to create a standard URI for a web service?
Below are the best practices that should be followed while creating a standard URI:
Use Plural Noun: We should use plural noun to define the resources. For eg., To identify users as a resource ‘users’ should be used.
Avoid using spaces: Always use underscore(_) or hyphen(-) while using long resource name. For eg. use ‘devlabs_alliance’ instead of ‘devlabs alliance’
Use Lower case letters: Use lower case letter in the URI.
Maintain backward compatibility: Since WebService is a public service, so a URI once made public should always be available. If URI gets updated, then the older URI should be redirected to new URI using HTTP status code, 300.
Use HTTP Verb: Always use HTTP verbs like GET, PUT, POST or DELETE to do any operation on the resource.



11. What is statelessness in RESTful Webservices?
Below are the advantages of statelessness in RESTFUL web services:
Each method request can be treated independently by Web services.
Web services are not required to maintain client’s previous interactions. It helps in simplifying application design.
RESTFUL Web services work seamlessly with HTTP protocol as HTTP is itself a statelessness protocol.


12. What are the advantages of statelessness in RESTFUL Webservices?
Below are the advantages of statelessness in RESTFUL web services:
Each method request can be treated independently by Web services.
Web services are not required to maintain client’s previous interactions. It helps in simplifying application design.
RESTFUL Web services work seamlessly with HTTP protocol as HTTP is itself a statelessness protocol.


13. What are the disadvantages of statelessness in RESTFUL Webservices?
Below is the major disadvantage of statelessness in RESTFUL web services:
Web services are required to get extra information in each request and then it needs to interpret that to get the client’s state, in case client interactions are to be taken care of.



14. Explain the architectural style for creating web API.
Below is the architectural style for creating web API:
HTTP is used for client server communication
XML/JSON is used as formatting language
Simple URI is used as the address for the services
Stateless communication is there


15. What is Caching in REST API?
Caching refers to a process when server stores response in client itself so that a client needs not to make server request for same resource again and again.

A server response should contain an information about how a caching is to be done. This helps a client to know whether it needs to cache some response for a period of time or caching the server response is not needed.


16. What are the best practices for caching?
Below are the best practices to be followed while caching:
Always keep the expiry date of static contents like images, css, JavaScript cacheable, to 2-3 days. Never keep a high expiry date.
Always cached the Dynamic contents just for few hours only.



17. What is JAX-RS?
 JAX-RS stands for JAVA API for RESTFUL Web Services. It is a JAVA based programming language API and specification that is used to provide support for created RESTful Webservices.

JAX-RS makes heavy use of annotations that are available from Java SE 5 to simplify development of JAVA based web services and their deployment. It also provides supports to create clients for RESTful web services.


18. List out the tools or API for developing or testing web api.
The testing tools for webservices for REST API are:
Spring REST web service using MVC
Jersey API
Axis
CFX
Restlet



19. What are the best practices to be followed while designing a secure RESTFUL web service?
Below are the best practices to be followed while designing a RESTful web service −
Validation: Ensure validation of all inputs on the server. Always protect your server from SQL injection attacks.
Session based authentication: Always use session based authentication to authenticate a user whenever a request is made to a Web Service method.
No sensitive data in URL: Never keep username, password or session token in URL , these values should always be passed to Web Service via POST method.
Restriction on Method execution: Always allow restricted use of methods like GET, POST, DELETE.
Validate Malformed XML/JSON: Always check that well formed input is passed to a web service method.
Throw generic Error Messages: A web service method should always use HTTP error messages like 403 to show access forbidden etc.





Saturday, April 17, 2021

How to Fake or Mock an API with JSON Server : Simple and Easy steps




******************************************************************************
How to Fake or Mock an API with JSON Server
******************************************************************************

JSON Server is an easy and quick-to-set-up module that you can use to fake or mock an API.


Getting Started:

1. Install node.JS on your system
2. Exeute below command to install json-server globally 
     npm install -g json-server

3. Create the db.json file in folder
Eg. C://User/json-server/db.json

4. db.json file contains below simple json, you can have any complex json in db.json file.

4. Once the db.json file is created, navigate to the folder where the file is saved.
From the folder path, open a command widow and type the command

json-server --watch db.json

5. Now check if you can able to access json server and it is up and running by hitting 'http://localhost:3000'
6. Open POSTMAN, Create GET request with API 'http://localhost:3000/employees'
Hit Send button
You should be able to see the response
Now, you have successfully faked REST APIT with json server and you can play around with your json server with CRUD operations.
------------------------------------------------------------------------------

Saturday, January 30, 2021

Latest top 10 API Automation Interview Questions and Answer Set 4

 






1. What are the static imports we need to do in rest-Assured?
import static io.restassured.RestAssured.*;
import static io.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matcher.*;


2. Write a code snipped GET to fetch the information from the server and validate the Request body
//Get Place ---> In get place, there no Json Body, everything will be in URL. and query parameter

Method-1 

            public static void main(String[] args) {
given()
.queryParam("page", "2")
.auth().none()
.header("Content-type","application/json")
.contentType(ContentType.JSON)
.when()
.get("https://reqres.in/api/users")
.then()
.statusCode(200)
.body(
"page", equalTo(2),
"per_page", equalTo(6),
"total", equalTo(12), 
"total_pages", equalTo(2)
);
System.out.println("successfully executed");
}


Method- 2


 Response getResponse = 
given().log().all()
.queryParam("page", "2").auth().none()
 .header("Content-type","application/json") 
.contentType(ContentType.JSON)
.when()
.get("https://reqres.in/api/users");
    
//  getResponse.prettyPrint();   //print response
  
  System.out.println("Response is: "+getResponse.getBody().asString());
  System.out.println("Status code is: "+getResponse.statusCode());
  System.out.println("Response time is: "+getResponse.getTime());



2. Write a code snipped GET to fetch the information from the server and validate the Request body - In different style

public void getWeatherDetailsWithCorrectCityNameTest(String users){

//1. define the base url
//https://reqres.in/api

RestAssured.baseURI = "//https://reqres.in/api";

//2. define the http request:
RequestSpecification httpRequest = RestAssured.given();

//3. make a request and execute the request:
Response response = httpRequest.request(Method.GET, "/"+users);

//4. get the response body:
String respBody = response.getBody().asString();
System.out.println("Response Body is: "+ respBody );
//validate city name or validate the key or value
Assert.assertEquals(respBody.contains(users), true);

//5. get the status code and validate it:
int statusCode = response.getStatusCode();
System.out.println("the status code is: "+ statusCode);

Assert.assertEquals(statusCode, 200);

System.out.println("the status line is: "+ response.getStatusLine());

//6. get the headers:
Headers headers = response.getHeaders();
System.out.println(headers);

String contentType = response.getHeader("Content-Type");
System.out.println("the value of content-type header is: "+ contentType);

String contentLength = response.getHeader("Content-Length");
System.out.println("the value of Content-Length header is: "+ contentLength);



3. Write a code snipped for POST request and validate the Request body
  
Method 1:

public class PostAPI {

static String requestPayload = "{\r\n"
+ "    \"name\": \"morpheus\",\r\n"
+ "    \"job\": \"leader\"\r\n"
+ "}";
public static void main(String[] args) {
given()
.auth().none()
.header("Content-type","application/json")
.contentType(ContentType.JSON)
.when()
.body(requestPayload)
.post("https://reqres.in/api/users")
.then()
.statusCode(201)
.body(
"name", equalTo("morpheus"),
"job", equalTo("leader")
 
);
}
}


Method 2

public class PostAPI {

static String requestPayload = "{\r\n"
+ "    \"name\": \"morpheus\",\r\n"
+ "    \"job\": \"leader\"\r\n"
+ "}";
public static void main(String[] args) {
Response getResponse = 
given()
.auth().none()
.header("Content-type","application/json")
.contentType(ContentType.JSON)
.when()
.body(requestPayload)
.post("https://reqres.in/api/users");
System.out.println("Response is :"+getResponse.getBody().asString());
System.out.println("Status code is :"+getResponse.statusCode());
System.out.println("Response time is: "+getResponse.getTime());
}
}


4. Write a code snipped for POST request and passing Request body in the form of Map object

Pre-requisites - you need to update update jackson databind dependency

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.5</version>
</dependency>



public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("name", "morpheus");
map.put("job", "leader");
Response getResponse = 
given()
.auth().none()
.header("Content-type","application/json")
.contentType(ContentType.JSON)
.when()
.body(map)
.post("https://reqres.in/api/users");
System.out.println("Response is :"+getResponse.getBody().asString());
System.out.println("Status code is :"+getResponse.statusCode());
System.out.println("Response time is: "+getResponse.getTime());
}



5. Write a code snipped for POST request and passing Request body from external file

public static void main(String[] args) {
Response getResponse = 
given()
.auth().none()
.header("Content-type","application/json")
.contentType(ContentType.JSON)
.when()
.body(new File(./PayLoad.json)).log().all()
.post("https://reqres.in/api/users");
System.out.println("Response is :"+getResponse.getBody().asString());
System.out.println("Status code is :"+getResponse.statusCode());
System.out.println("Response time is: "+getResponse.getTime());
}



6. How to do Schema validation in Rest assured?
Steps:
Pre-requisite:
Update pom.json with jsonschema validator dependencydependency
2. Create schema.json file in project root level
3. Paste generated json schema in schema.json file
4. Write following code snippet to validate the json schema


@Test
public void ValidateJsonSchema()

Response response =   given().log().all()
  .contentType("application/json")
  .body(para)       //para is your body
  .when()
  .post("https://reqres.in/api/users");
   
  response.then().body(JsonSchemaValidator.matchesJsonSchema(new File("schema.json")));



6. what exception Rest Assured will throw when we pass wrong content-type ?
It will throw 'Unsupported media type'

7. How do you extract path parameter from response in Rest Assured ?
Using jsonpath

8. How to pass dynamic body for Post Request in Rest Assured?
We can provide Request payload using following way:
1. POJO
2. MAP object, 
3. placeholder JSONfiles, 
4. as String


9. How to declare the API details in Rest Assured Test?
We can declare API details in BDD format as below 
Given(), 
When(), 
Then()


10. Name The Most Commonly Used HTTP Methods Supported By REST?
    There are a few HTTP methods in REST which are more popular.

GET -It requests a resource at the request-URL. It should not contain a request body as it will get discarded. Maybe it can be cached locally or on the server.
2. POST – It submits information to the service for processing; it should typically return the modified or new resource.
3. PUT – At the request URL it updates the resource.
4. DELETE – It removes the resource at the request-URL.
5. OPTIONS -It indicates the supported techniques.
6. HEAD – It returns meta information about the request URL.


11. What Is URI? Explain Its Purpose In REST Based Web Services. What Is Its Format?
    URI stands for Uniform Resource Identifier. URI is the identifier for the resource in REST architecture.

The purpose of a URI is to locate a resource(s) on the server hosting the web service. A URI is of the following format-

<protocol>://<service-name>/<ResourceType>/<ResourceID>


12. How to compare the response values with Rest Assured Assertion?
    Example :
given().
.parameters("firstName", "John", "lastName", "Doe")
.when()
.post("/greetXML").
.then()
.body("greeting.firstName", equalTo("John")).
.body("greeting.lastName", equalTo("Doe"));


13. How to Insert cookies in Testing the API using Rest Assured?
         given().cookie("username", "John")
        .when().get("/cookie")
        .then().body(equalTo("username"));

14. How to Insert headers in Testing the API using Rest Assured?

        given().header("MyHeader", "Something").


15. How to Validate Response Headers with Rest Assured?
    
To print all the header:

  @Test
public void validateHeader() {

Response response = given().get("http://localhost:3000/employees");
Headers a = response.getHeaders();
for (Header header : a) {
System.out.println(header.getName() + ":" + header.getValue());
}

}


To Validate the header:

        @Test
        public void validateHeader() {
                Response response = given().get("http://localhost:3000/employees");

                String head = response.getHeader("Content-Type");
                System.out.println(head);
                assertEquals(head, "application/json");
        }


16. How to handle Basic Authentication with Rest Assured?

        given().auth().preemptive().basic("username","password")
        .when().get("/secured/hello")
        .then().statusCode(200);

17. How to iterate and validate the key in JSON Array?
We need to use the method getList()  which return List<String>
Code snippet as follows

Refer JSON - URI "https://reqres.in/api/users"

 public static void verifyStatusEmailId(){
                Response resp = given().when().get("https://reqres.in/api/users");

List<String> ids = resp.jsonPath().getList("data.email");
                
                for (String i : ids) {
System.out.println(i);
if (i.contentEquals("eve.holt@reqres.in")) {
System.out.println("eve holt is present in the response body");
}
}
}
Output will be - "eve holt is present in the response body"


18. How to count and assert the count of JSON Array?

Refer JSON - URI "https://reqres.in/api/users"

 public static void countJsonArray(){
                Response resp = given().when().get("https://reqres.in/api/users");

List<String> jsonResponse = resp.jsonPath().getList("data"); System.out.println(jsonResponse.size()); System.out.println("The number of data in the list is : " + jsonResponse.size()); assertEquals(jsonResponse.size(), 6);
}
output will be --true


19. How to read particular key in JSON Array?
We can do it by using getString() method which return String.


Refer JSON - URI "https://reqres.in/api/users"

 public static void verifySecondUsername(){
                Response resp = given().when().get("https://reqres.in/api/users");

String usernames = resp.jsonPath().getString("data[1].email"); System.out.println("fetch the second email from data list: " + usernames);
}
Output will be - fetch the second email from data list: Janet



20. How to fetch the value from JSON Array using MAP?
Step 1. We can do it by using getMap() method which return Map<String,String>
Step2. Then need to iterate throguh map using KeySet() and which will return Set<String>, we 
            would need to type cast with List
Steps3. Then we can call get() method to get the value. like get("first_name")


Refer JSON - URI "https://reqres.in/api/users"

 public static void verifyFirstName(){
                Response resp = given().when().get("https://reqres.in/api/users");

Map<String, String> dataEmp = resp.jsonPath().getMap("data[2]"); System.out.println("Using MAP: "+dataEmp);
List<String> tset = new ArrayList<>(dataEmp.keySet()); System.out.println("Fetch firtsname using map and get: " + dataEmp.get("first_name"));
}
Output will be - Fetch firtsname using map and get: Emma





21. Advantes of Rest Assured are listed below:-
  • It is an Open source i.e. free.
  • It requires less coding compare to Apache Http Client.
  • Initial setup is easy and straightforward before you hit any endpoint.
  • Easy parsing and validation of response in JSON and XML.
  • It follows BDD keywords like given(), when(), then() which makes code readable and supports clean coding. This feature is available from version 2.0.
  • Very rich in readymade assertion
  • Quick assertion for status code and response time.
  • Powerful logging mechanism.
  • Can be easily integrated with other Java libraries like TestNG, Junit for Test Framework and Extent Report , Allure Report for reporting purpose.
  • Very good support for different authentication mechanism for APIs.
  • Can be integrated with Selenium-Java to achieve End to End automation.
  • Supports JsonPath and XmlPath which helps in parsing JSON and XML response. Rest Assured by default integrates both.
  • Can be used to verify Json Schema using JSON Schema Validation library.
  • Includes XML schema validation
  • Can be integrated with Maven and CICD.
  • REST Assured 4.1.2 is released. It adds support for Java 13.

Disadvantages of Rest assured:-

  • Does not support SOAP APIs explicitly.
  • Less community support
  • Requires good Java programming knowledge

22. How to handle Oauth2.0 in rest assured.
Oauth is type of authorization and which is different from rest of the authorization,
As we use basic authorization for primary application where username and password requires and we can login to application and get the appropriate data.
but in case of Oauth is designed to let third party applications access the user data in some form of security.
Realtime example: Suppose you are signing up to a client application MakeMyTrip to book a flight but before login into MakeMyTrip application if you
do not have account first you need to create an account so that you can sign into MakeMyTrip application. MakeMyTrip application needs your details for signing up like first name, last name, profile picture, mobile number etc. Usually we get different way to sign in to application Like direct sign in by giving email id and password another option signing via Facebook.
When you click Facebook button then pop up gets open and it ask you grant access on your Facebook app and when you click on allow button it means you allowing the Facebook data with 3rd party MakeMyTrip application. But how would Facebook know which application is this and Facebook can not simply share the data to any application. so here client registration came into the picture where MakeMyTrip will provide call back URL to Facebook so Facebook will knows where to redirect after sign up via Facebook.

//First we need to get the access token for which we need to provide Client id and Secret id as Basic authentication. In your case clientID and Secrete Key will be different, click on below URL and follow the instruction to get the clientID and SecretKey

Below code snipped illustrate the scenario
//Here am using MakeMyTrip API



public class POSTAPI_getAccessToken {

static String clientId = "AUv-PH2Lt58UdTjNZX3LxuSaD93808ovCdmCn4amO-TPcvg7kJySIXbe0u6WWT3wUKfP77PrFcpJo8ay";

static String secretId = "EPEwtv8pTr-Y7VGWLk_0JxJRfehuRBBG5xQEKVpWgNXSfqtWn-YQiFvDVSwZLfrPwDQJeME4I4b9Z1AI";

static String accessToken = "";

@Test(priority = 1)
public void getAccessToken() {

Response response = 
                                 given()
                                .auth().preemptive().basic(clientId, secretId)
.param("grant_type", "client_credentials")
                                .log().all()
.post("https://api-m.sandbox.paypal.com/v1/oauth2/token");

response.prettyPrint();
System.out.println("Statuc code is " + response.statusCode());

//Here am storing the access token in string variable "accessToken" so that i can use this variable for automating other API i.e POST,PUT,PATCH

accessToken = response.getBody().path("access_token");
System.out.println("Access token is " + accessToken);
}


@Test(priority = 2, dependsOnMethods = "getAccessToken")
public void createOrder() {

String payload = "{\r\n"
+ "  \"intent\": \"CAPTURE\",\r\n"
+ "  \"purchase_units\": [\r\n"
+ "    {\r\n"
+ "      \"amount\": {\r\n"
+ "        \"currency_code\": \"USD\",\r\n"
+ "        \"value\": \"100.00\"\r\n"
+ "      }\r\n"
+ "    }\r\n"
+ "  ]\r\n"
+ "}";

Response response = given()
.contentType(ContentType.JSON)
.auth()
.oauth2(accessToken)
.body(payload)
.log().all()
.post("https://api-m.sandbox.paypal.com/v2/checkout/orders");
response.prettyPrint();


23. How to handle expiring based token in rest assured?
1. Create a method for generating token and call that method as a prerequisite for all @Test methods

2. 
    RestAssured.baseURI = "http://localhost:8080";
    SessionFilter seassion = new SessionFilter();
    
    String login = given()
                            .log().all()
                            .header("Content-Type", "application/json")
                            .body("{ \"username\": \"abc\", \"password\": \"xyz\" }")
                            .filter(seassion)
                            .when()
                            .post("/rest/auth/1/session")
                            .then().log().all().extract().response().asString();


3. If using cucumber create one step and keep it in Background




23. Create the utility to parse the dynamic JSON?
How to parse dynamic JSON?
How to parse nested JSON?

public class ParseDynamicJson {

public static void parseObject(JSONObject json, String key) {
// System.out.println(json.has(key));
System.out.println(json.get(key));
}

public static void getKey(JSONObject json, String key) {

boolean exists = json.has(key);
Iterator<?> keys;
String nextKeys;

if (!exists) {
keys = json.keys();
while (keys.hasNext()) {
nextKeys = (String) keys.next();
try {

if (json.get(nextKeys) instanceof JSONObject) {

if (exists == false) {
getKey(json.getJSONObject(nextKeys), key);
}

} else if (json.get(nextKeys) instanceof JSONArray) {
JSONArray jsonarray = json.getJSONArray(nextKeys);
for (int i = 0; i < jsonarray.length(); i++) {
String jsonarrayString = jsonarray.get(i).toString();
JSONObject innerJSOn = new JSONObject(jsonarrayString);

if (exists == false) {
getKey(innerJSOn, key);
}

}

}

} catch (Exception e) {
}

}

} else {
parseObject(json, key);
}

}

public static void main(String[] args) {

String inputJson = "{\r\n"
+ "    \"name\": \"morpheus\",\r\n"
+ "    \"job\": \"leader\",\r\n"
+ "    \"id\": \"675\",\r\n"
+ "    \"createdAt\": \"2021-03-20T18:24:54.124Z\"\r\n"
+ "}";

//We need to convert String to JSON Object first since getKey method accespt JSONObject
JSONObject inputJSONOBject = new JSONObject(inputJson);

getKey(inputJSONOBject, "job");

}

}

Output will be : leader
In above example I have provided the simple JSON, you can provided any complex JSON.


24. Create the utility to validate the key from JSON Object?


public static void responseKeyValidationFromJsonObject(Response response, String key)
    {
JSONObject json = new JSONObject(response.getBody().asString());
json.get(key);
System.out.println("using JSON Object: " +json.get(key));
     }


25. How to get the value by using from JSON object.

We can do it by using JsonPath class .

JsonPath js = new JsonPath(inputJson);
Object name =js.get("firstname");
System.out.println(name);

 OR

JsonPath jsonPathValue = response.jsonPath();
String cityVal = jsonPathValue.get("City");
System.out.println("the value of city is: "+ cityVal);
Assert.assertEquals(cityVal, city)

How to install Java on EC2

***************************************** How to install Java on EC2 ***************************************** To be continued, In this post...

All Time Popular Post