Rest Assured

 Q : Difference between REST API and SOAP API

Ans:



Q:Difference Between Web Service vs Web API

Ans:



Q: What is REST Assured?

Ans:

REST Assured is a Java library RESTful APIs testing. It is mostly used to test web applications that are based on JSON and XML.
It supports multiple methods likely GET, PUT, POST, PATCH, and DELETE etc.


Q : What is the difference between PUT and POST?

Ans:

“PUT” puts a file or resource at a particular URI and exactly at that URI. 
If there is already a file or resource at that URI, PUT changes that file or resource. If there is no resource or file there, PUT makes one

POST sends data to a particular URI and expects the resource at that URI to deal with the request.
The web server at this point can decide what to do with the data in the context of specified resource

PUT is idempotent meaning, invoking it any number of times will not have an impact on resources.

POST is not idempotent, meaning if you invoke POST multiple times it keeps creating more resources

Q: Advantages of using REST-assured instead of Postman to automate RESTful services?

Ans:

Advantages of using REST Assured over Postman:

a. For the REST-assured, we can customize the reports. Postman, on the other hand, does not allow us to customize the reports.
b. Code can be reused in REST assured, as it is a Java library, whereas code reusability is not possible in Postman.
c. For each collection, we can only submit one data file to the Postman automation runner. However, there is no such restriction for REST-assured.


Q: Different HTTP methods supported by REST?

Ans: 

a. GET : It requests a resource at the request URL to fetch some information from the server. It should not contain a request body. Maybe it can be cached locally or on the server.
b. POST : It submits information to the service for processing; it should typically return the modified or new resource
c. PUT : At the request URL it update the resource
d. DELETE : At the request URL it removes the resource
e. OPTIONS : It indicates which techniques are supported
f. HEAD : About the request URL it returns meta information


Q: Why do we use static import in Rest Assured?

Ans:

Static import is a Java programming language feature that allows members (fields and methods) that have been scoped as public static within their container class 
to be used in Java code without mentioning the class in which the field has been defined.

/**
 * this is static import to avoid writing into front of every method call of RestAssured
 */
import static io.restassured.RestAssured.*;

public class StaticTest 
{
@Test
public void teststaticimport() {

// with static import
given();


// without static import
/**
*  import io.restassured.RestAssured;
*  RestAssured.given();
*/

}
}


Q: What is method chaining in rest assured ?

Ans:

In object-oriented programming languages, method chaining is a syntax for invoking numerous method calls. 
Each method returns an object, allowing multiple calls to be chained together in a single line without the need for variables to hold interim results.

For example in rest assured all methods chained together with dots.

          given()
.baseUri(baseUri)
.queryParam(parameterName, parameterValues)
.accept(contentType).
.when()
.then();


Q: How to validate the response of REST API in Rest Assured?

Ans:

1. GET Request Syntax
A GET request is used to retrieve data from the server. Here's the typical syntax for a GET request using RestAssured:

import io.restassured.RestAssured;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;

public class GetRequestExample {
    public static void main(String[] args) {
        // Base URI setup (commonly used in real projects)
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

        // Perform a GET request
        Response response = given()
            .header("Accept", "application/json") // Optional: Set request headers
        .when()
            .get("/posts/1") // Specify the endpoint
        .then()
            .statusCode(200) // Validate the status code
            .body("userId", equalTo(1)) // Validate specific fields in the response body
            .extract().response(); // Extract the response if needed

        // Print the response for debugging (optional)
        System.out.println("Response Body: " + response.getBody().asString());
    }
}
Explanation:
Base URI: This sets the base URL for all requests. In real projects, this is often set in a configuration file or a base test class.
given(): Sets up the request, where you can add headers, parameters, etc.
when(): Specifies the action, such as get(), post(), etc.
then(): Validates the response, where you can check status codes, response body content, etc.
extract().response(): This is used to extract the response if you need to work with it further in your test.


2. POST Request Syntax
A POST request is used to send data to the server, often to create a new resource. Here's a typical syntax for a POST request:

import io.restassured.RestAssured;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;

public class PostRequestExample {
    public static void main(String[] args) {
        // Base URI setup
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

        // JSON payload (in real projects, this could be read from a file or generated dynamically)
        String jsonPayload = "{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }";

        // Perform a POST request
        Response response = given()
            .header("Content-Type", "application/json") // Set request headers
            .body(jsonPayload) // Attach the payload
        .when()
            .post("/posts") // Specify the endpoint
        .then()
            .statusCode(201) // Validate the status code
            .body("title", equalTo("foo")) // Validate specific fields in the response body
            .extract().response(); // Extract the response if needed

        // Print the response for debugging (optional)
        System.out.println("Response Body: " + response.getBody().asString());
    }
}
Explanation:
JSON Payload: The body of the POST request, often represented as a string or constructed using Java objects that are serialized to JSON.
header("Content-Type", "application/json"): Sets the content type of the request. This is essential when sending JSON data.
body(jsonPayload): Attaches the payload to the request.
post("/posts"): Specifies that you are making a POST request to the /posts endpoint.



Q: What is jsonPath in Rest Assured?

Ans:

JsonPath (io.restassured.path.json.JsonPath) is a way to get values from an Object document without using XPath.
While retrieving an object from the document, it follows the Groovy GPath syntax. It can be thought of as a JSON-specific version of XPath. 
For example, consider the following Object document.

Sample JSON:

{ "company": {
   "employee": [
    { "id": 1,
      "name": "Name1",
      "role": "Admin"
    },
    { "id": 2,
      "name": "Name2",
      "role": "User"
    },
    { "id": 3,
      "name": "Name3",
      "role": "User"
    }
  ]
  }
 }


Response employeesResponse = RestAssured.given().request(Method.GET, "/all");
JsonPath jsonPathObj = employeesResponse.jsonPath();

//get a list of all employees id:
List<String> employeeIds = jsonPathObj.get("company.employee.id");

//get the first employee name:
String empName = jsonPathObj.get("company.employee[0].name");


Q: How to log the request and response in case of validation failed in Rest Assured?
Ans:

If a test validation fails, log().ifValidationFails() logs everything in the request and response.

    /**
     * Log the request and response details if validation fails.
     */
    @Test
    public void testIfValidationFails() {
        given().
        baseUri("http://localhost:8080").
        header("Key", "Value").
        log().ifValidationFails().
        when().
        get("/employees").
        then().
        log().ifValidationFails().
        assertThat().
        statusCode(200);
    }


Q: How to find all employees ids from 1 to 10 using Rest Assured jsonPath?
Ans:

Response employeesResponse = RestAssured.given().request(Method.GET, "/all");
JsonPath jsonPathObj = employeesResponse.jsonPath();

//get all employees id between 1 and 10
List<Map> employees = jsonPathObj.get("company.employee.findAll { employee -> employee.id >= 1 && employee.id <= 10 }");
 
Q: How to send a POST Request in Rest Assured?
Ans:

    @Test
    public void testPostEmployee() throws JSONException 
   {
        JSONObject empParams = new JSONObject();
        empParams.put("name", "json Shukla");
        empParams.put("role", "Supervisor");

        given()
                .contentType(ContentType.JSON)
                .body(empParams.toString())
                .log().all()

                .when()
                .post("http://localhost:8080/employee")

                .then()
                .assertThat().statusCode(200)
                .body("name", equalTo("json Shukla"))
                .body("role", equalTo("Supervisor"))
                .log().all();

    }

Q: How can we get size of JSON array in Rest assured?
Ans:

// base URL to call
RestAssured.baseURI = "http://localhost:8080/employees/get";

Response employeesResponse = RestAssured.given().request(Method.GET, "/all");
List<String> employees = employeesResponse.jsonPath().getList("ORG.EMPLOYEES.id");
System.out.println(employees.size());



Q: What is Serialization and Deserialization in Java?
Ans:

Serialization is the process of converting an object's state into a byte stream.
Deserialization is the process of recreating the actual Java object in memory using the byte stream. The object is kept alive through this approach.

Serialization and Deserialization:

Serialization and Deserialization

public class SerilDeserializationPOST{
@Test(priority=1)
public  void createuserserializable()
{
Userdetails users =new Userdetails();
users.setJob("S/W");
users.setName("Dheeraj");
given()
.contentType(ContentType.JSON)
.body(users)
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201);
}

@Test(priority=2)
public  void getuserdeserializable()
{
Userdetails users =get("https://reqres.in/api/users/1").as(Userdetails.class);
System.out.println(users.toString());

}

public class Userdetails {
public String name;
public String job;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}

}

=== with jakson library ====

Ans:
Serialization: Java Object to JSON
Serialization is the process of converting a Java object into a JSON string.

Step-by-Step Example
Create a POJO (Plain Old Java Object):
This is the Java class you want to serialize.


public class User {
    private String name;
    private int age;
    private String email;

    // Constructors
    public User() {}

    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    // Getters and Setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Serialize the Object to JSON:
Use Jackson's ObjectMapper to convert the object to a JSON string.


import com.fasterxml.jackson.databind.ObjectMapper;

public class SerializationExample {
    public static void main(String[] args) throws Exception {
        User user = new User("John Doe", 30, "john.doe@example.com");

        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeValueAsString(user);

        System.out.println(jsonString);
    }
}
Output:

{"name":"John Doe","age":30,"email":"john.doe@example.com"}

Use Serialized Object in RestAssured:

You can use the serialized JSON in your API request.

import static io.restassured.RestAssured.*;
import static io.restassured.http.ContentType.JSON;

public class RestAssuredSerialization {

    public static void main(String[] args) {

        User user = new User("John Doe", 30, "john.doe@example.com");

        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeValueAsString(user);

        given()
            .contentType(JSON)
            .body(jsonString)
        .when()
            .post("https://api.example.com/users")
        .then()
            .statusCode(201);
    }
}

3. Deserialization: JSON to Java Object

Deserialization is the process of converting a JSON string back into a Java object.

Step-by-Step Example
Example JSON Response:
Suppose you receive the following JSON response from an API:

{
    "name": "John Doe",
    "age": 30,
    "email": "john.doe@example.com"
}

Deserialize JSON to Java Object:

import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;

public class DeserializationExample {
    public static void main(String[] args) throws Exception {

        Response response = 
            given()
            .when()
                .get("https://api.example.com/users/1")
            .then()
                .statusCode(200)
                .extract().response();

        String jsonResponse = response.asString();
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(jsonResponse, User.class);

        System.out.println(user.getName());  // Output: John Doe
        System.out.println(user.getAge());   // Output: 30
        System.out.println(user.getEmail()); // Output: john.doe@example.com
    }
}

4. Putting It All Together

You can combine serialization and deserialization in a typical RestAssured test where you send a serialized object in a POST request and then deserialize the response.

j
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;
import static io.restassured.http.ContentType.JSON;

public class RestAssuredExample {
    public static void main(String[] args) throws Exception {

        // Step 1: Serialize the object
        User user = new User("Jane Doe", 25, "jane.doe@example.com");
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeValueAsString(user);

        // Step 2: Send POST request with serialized JSON
        Response response = 
            given()
                .contentType(JSON)
                .body(jsonString)
            .when()
                .post("https://api.example.com/users")
            .then()
                .statusCode(201)
                .extract().response();

        // Step 3: Deserialize the response
        User createdUser = mapper.readValue(response.asString(), User.class);

        // Step 4: Verify the deserialized object
        System.out.println(createdUser.getName());  // Output: Jane Doe
        System.out.println(createdUser.getAge());   // Output: 25
        System.out.println(createdUser.getEmail()); // Output: jane.doe@example.com
    }
}

Q: What are different status code ?

Ans:

a. 200 (OK)
It indicates that the REST API successfully carried out whatever action the client requested and that no more specific code in the 2xx series is appropriate.
Unlike the 204 status code, a 200 response should include a response body. The information returned with the response is dependent on the method used in the request, for example:
GET an entity corresponding to the requested resource is sent in the response;
HEAD the entity-header fields corresponding to the requested resource are sent in the response without any message-body;
POST an entity describing or containing the result of the action;
TRACE an entity containing the request message as received by the end server.

b. 201 (Created)
A REST API responds with the 201 status code whenever a resource is created inside a collection. There may also be times when a new resource is created as a result of some controller action, in which case 201 would also be an appropriate response.
The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field.
The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with a 202 (Accepted) response instead.

c. 202 (Accepted)
A 202 response is typically used for actions that take a long while to process. It indicates that the request has been accepted for processing, but the processing has not been completed. The request might or might not be eventually acted upon, or even maybe disallowed when processing occurs.
Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent’s connection to the server persist until the process is completed.
The entity returned with this response SHOULD include an indication of the request’s current status and either a pointer to a status monitor (job queue location) or some estimate of when the user can expect the request to be fulfilled.

d. 204 (No Content)
The 204 status code is usually sent out in response to a PUT, POST, or DELETE request when the REST API declines to send back any status message or representation 
in the response message’s body.
An API may also send 204 in conjunction with a GET request to indicate that the requested resource exists, but has no state representation to include in the body.
If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input 
for actions to take place without causing a change to the user agent’s active document view. However, any new or updated metainformation SHOULD be applied to 
the document currently in the user agent’s dynamic view.
The 204 response MUST NOT include a message-body and thus is always terminated by the first empty line after the header fields.

e. 301 (Moved Permanently)
The 301 status code indicates that the REST API’s resource model has been significantly redesigned, and a new permanent URI has been assigned to the client’s requested resource.
The REST API should specify the new URI in the response’s Location header, and all future requests should be directed to the given URI.
You will hardly use this response code in your API as you can always use the API versioning for the new API while retaining the old one.

f. 302 (Found)
The HTTP response status code 302 Found is a common way of performing URL redirection. An HTTP response with this status code will additionally provide 
a URL in the Location header field. The user agent (e.g., a web browser) is invited by a response with this code to make a second. Otherwise identical, request to the 
new URL specified in the location field.
Many web browsers implemented this code in a manner that violated this standard, changing the request type of the new request to GET, regardless of the type 
employed in the original request (e.g., POST). RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request.
The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.

g. 303 (See Other)
A 303 response indicates that a controller resource has finished its work, but instead of sending a potentially unwanted response body, it sends the 
client the URI of a response resource. The response can be the URI of the temporary status message, or the URI to some already existing, more permanent, resource.
Generally speaking, the 303 status code allows a REST API to send a reference to a resource without forcing the client to download its state. Instead, the client may 
send a GET request to the value of the Location header.
The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.

h. 304 (Not Modified)
This status code is similar to 204 (“No Content”) in that the response body must be empty. The critical distinction is that 204 is 
used when there is nothing to send in the body, whereas 304 is used when the resource has not been modified since the version specified by the request headers 
If-Modified-Since or If-None-Match.
In such a case, there is no need to retransmit the resource since the client still has a previously-downloaded copy.
Using this saves bandwidth and reprocessing on both the server and client, as only the header data must be sent and received in comparison to the entirety 
of the page being re-processed by the server, then sent again using more bandwidth of the server and client.

i. 307 (Temporary Redirect)
A 307 response indicates that the REST API is not going to process the client’s request. Instead, the client should resubmit the request to the URI 
specified by the response message’s Location header. However, future requests should still use the original URI.
A REST API can use this status code to assign a temporary URI to the client’s requested resource. For example, a 307 response can be used to shift a client request over to another host.
The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a 
short hypertext note with a hyperlink to the new URI(s). If the 307 status code is received in response to a request other than GET or HEAD, the user agent 
MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

j. 400 (Bad Request)
400 is the generic client-side error status, used when no other 4xx error code is appropriate. Errors can be like malformed request syntax, invalid request 
message parameters, or deceptive request routing etc.
The client SHOULD NOT repeat the request without modifications.

k. 401 (Unauthorized)
A 401 error response indicates that the client tried to operate on a protected resource without providing the proper authorization. 
It may have provided the wrong credentials or none at all. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.
The client MAY repeat the request with a suitable Authorization header field. If the request already included Authorization credentials, then the 401 response 
indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already 
attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information.

l. 403 (Forbidden)
A 403 error response indicates that the client’s request is formed correctly, but the REST API refuses to honor it, i.e., the user does not have the 
necessary permissions for the resource. A 403 response is not a case of insufficient client credentials; that would be 401 (“Unauthorized”).
Authentication will not help, and the request SHOULD NOT be repeated. Unlike a 401 Unauthorized response, authenticating will make no difference.

m. 404 (Not Found)
The 404 error status code indicates that the REST API can’t map the client’s URI to a resource but may be available in the future. Subsequent requests by the client are permissible.
No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally 
configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly 
used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

n. 405 (Method Not Allowed)
The API responds with a 405 error to indicate that the client tried to use an HTTP method that the resource does not allow. 
For instance, a read-only resource could support only GET and HEAD, while a controller resource might allow GET and POST, but not PUT or DELETE.
A 405 response must include the Allow header, which lists the HTTP methods that the resource supports. For example:
Allow: GET, POST

o. 406 (Not Acceptable)
The 406 error response indicates that the API is not able to generate any of the client’s preferred media types, as indicated by the Accept request header. 
For example, a client request for data formatted as application/xml will receive a 406 response if the API is only willing to format data as application/json.
If the response could be unacceptable, a user agent SHOULD temporarily stop receipt of more data and query the user for a decision on further actions.

p. 412 (Precondition Failed)
The 412 error response indicates that the client specified one or more preconditions in its request headers, effectively telling the REST API to carry out its request only if certain conditions were met. A 412 response indicates that those conditions were not met, so instead of carrying out the request, the API sends this status code.

q. 415 (Unsupported Media Type)
The 415 error response indicates that the API is not able to process the client’s supplied media type, as indicated by the Content-Type request header. For example, a client request including data formatted as application/xml will receive a 415 response if the API is only willing to process data formatted as application/json.
For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.

r. 500 (Internal Server Error)
500 is the generic REST API error response. Most web frameworks automatically respond with this response status code whenever they execute some request handler code that 
 raises an exception.
A 500 error is never the client’s fault, and therefore, it is reasonable for the client to retry the same request that triggered this response and hope to get a different response.
The API response is the generic error message, given when an unexpected condition was encountered and no more specific message is suitable.

s. 501 (Not Implemented)
The server either does not recognize the request method, or it cannot fulfill the request. Usually, this implies future availability (e.g., a new feature of a web-service API).



Q: What is the difference between path params and query params ?

Ans:
  • Path params are used to identify resources on the server while query params are used to sort/filter resources.
  • Query params are key-value-like pairs that appear after the question mark in the URL while path params come before the question mark.

How to pass Path Param:

@Test
void test() {
RestAssured.given()
.pathParam("user", "users/qaautomatonhub")
.when()
.get("https://http://localhost:4001/{user}")
.prettyPrint();
}

How to pass query Param:

 public void verifyRepos(){
        
        RestAssured.given()
                .queryParam("sort","created")
                .queryParam("direction","desc")
                .when().get("https://http://localhost:4001/users")
                .then().log().body();
    }



Q: How to upload a media file using Rest Assured?

Ans:

public void upload() 
{
File file = new File("myavatar.png");
Response resp= RestAssured.given().multiPart("media_url", file,"application/octet-stream").when()
.post("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&thumbs=True")
.then().extract().response();
String url=resp.path("url");
System.out.println(url);
}

Q: Can we write RestAssured.with() instead of RestAssured.given()?
Ans:

Yes we can use any of the above mentioned approach like

RequestSpecification request2 = RestAssured.with();
RequestSpecification request1 = RestAssured.given();

Both works in the same way, The only difference between {@link #with()} and {@link #given()} is syntactical.


Q: How to send Nested JSON object as payload?
Ans:

Ex: 

{
“workspace”: 
{

“name”:”myworkspace”,

“id”:”X123″

}
}

HashMap<String,Object> mainobj= new HashMap<String,Object>();
HashMap<String,String> subobj= new HashMap<String,String>();
subobj.put("name","QA");
subobj.put("id","X123");
mainobj.put("workspace",subobj);


Q: Write a code snippet to fetch cookies.

Ans:

Rest Assured Interview Questions


Q: Define a resource in REST.
Ans:

The REST architecture treats any content as a resource. This content includes HTML pages, text files, images, videos, or dynamic business information. 
A REST Server gives users access to these resources and modifies them, and URIs or global IDs identify each resource.


Q: what’s the best method of keeping sensitive data out of the log?
Ans:

Use a blacklist to prevent sensitive data from appearing in the log. Here’s how:

Set<String> headers = new HashSet<String>();
headers.add("X-REGION");
headers.add("content-type");

given().
baseUri("http://localhost:8080").
header("X-REGION", "NAM").

// blacklist headers
config(
config.logConfig(LogConfig.logConfig().blacklistHeaders(headers)))

// blacklist multiple headers
//config(config().logConfig(LogConfig.logConfig().blacklistHeader("Accept","set-cookie"))).

log().all().
when().
get("/employees").
then().assertThat().statusCode(200);


Q: What are the advantages of API Testing?
Ans:

a. API testing helps in core functionality by giving direct access to the application, without needing a user interface. It is helpful in detecting minor errors 
before they turn into major issues during GUI testing.
b. API testing uses less code than GUI testing so it gives better coverage. That’s hat it is time-effective too.
c. API testing is language-independent as data is exchanged using XML or JSON, which allows users to select any coding language when adopting an automation test service.
API can be easily integrated with GUI testing.


Q: What are the protocols used in API Testing?
Ans: 

These are the protocols used in API testing:
HTTP
REST
SOAP
UDDI
JMS
XML-RPC
JSON-RPC


Q:  What is URI?
Ans:
1. URI (Uniform Resource Identifier):
Definition: A URI is a string of characters that identifies a resource on the internet. It can be either a URL (Uniform Resource Locator) or a URN (Uniform Resource Name).

Example: https://api.example.com/users/123?active=true
In this case, the entire string is a URI because it identifies a resource on the internet.

2. Base URL:
Definition: The base URL is the starting point of a web address. It typically includes the protocol (http:// or https://), the domain name, and sometimes a port number.
Example: https://api.example.com
This part of the URL is the base URL and serves as the foundation for building the full API endpoint.

3. Endpoint:
Definition: An endpoint is a specific URL that allows you to access a particular resource or functionality on a server. It’s the path added to the base URL to form the full URL for an API call.
Example: /users/123
Combined with the base URL, the full endpoint is https://api.example.com/users/123.

4. Path Parameter:
Definition: Path parameters are variables in the URL path that allow you to pass data directly in the endpoint's URL. They are typically used to identify specific resources.
Example: /users/{userId}
If userId is a path parameter and you want to access the user with ID 123, the URL would be https://api.example.com/users/123.

5. Query Parameter:
Definition: Query parameters are key-value pairs added to the URL after a question mark (?). They are used to filter, sort, or refine the data that you retrieve from an API.
Example: ?active=true&sort=asc
Added to the base URL and endpoint, the full URL might look like https://api.example.com/users/123?active=true&sort=asc.


Q:  Which HTTP methods are used in REST and what do they do?

Ans:

GET    : Retrieves resource representation. Should be cacheable.
POST  : Creates a new subordinate resource. Not cacheable
PUT    : Updates existing resources. If the resource does not exist, then API may decide whether to create a new one or not.
PATCH     : Makes a partial update
DELETE   : Deletes the resource. Idempotent and not cacheable
OPTIONS : Describe the communication options for the target resource.
HEAD       : Asks for a response identical to that of a GET request, but without the response body.


Q: Can You explain the payload?

Ans: 
Payload/body is highly secured input data that is sent to API to process the request. The payload is usually in JSON format in REST API.

Q: What is client-Server Architecture ?

Ans : Document Link: https://bit.ly/3VS2AIX

Q: What are static import in Rest Assured ?

Ans:
      import org.testng.annotations.Test;
      import static io.restassured.RestAssured.*;
      import static org.hamcrest.Matchers.*;

     public class GetRequest {
@Test
public void getrequest()
{
given()
.when()
.get("URL")
.then()
.statusCode(200)
.statusLine("HTTP/1.1 200 OK")
.assertThat().body("name", equalTo("Deven Pandey"))
.header("Content-Type", "application/json; charset=utf-8");
}

   }

Q: How to pass your tocken in Rest Assured

Ans:
public void myTestMethod() {

       JSONObject requestBody = new JSONObject();
        requestBody.put("key1", "value1");
        requestBody.put("key2", "value2");

        // Set the base URI of your API
        RestAssured.baseURI = "https://api.example.com";

        // Create a request specification object
        RequestSpecification request = RestAssured.given();
        request.header("Authorization", "Bearer your_token_here");
        request.body(requestBody.toString());
        Response response = request.post("/endpoint");
        response.then().statusCode(200);
    }


Q: How to validate with API Response ?

Ans:
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;  //equalTo and hasitems methods comimg from this
import static org.hamcrest.Matchers.*;

public class BasicValidation {
@Test
public void basicValidation()
{
given()
.when()
.get("http://jsonplaceholder.typicode.com/posts/5")
.then()
.statusCode(200)
.statusLine("HTTP/1.1 200 OK")
.log().all();
}

@Test
public void respnseValidation()
{
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200)
.statusLine("HTTP/1.1 200 OK")
.body("data.first_name", equalTo("Janet"))
.log().all();
}
@Test
public void responsemultipleValidation()
{
given()
.when()
.get("https://reqres.in/api/users")
.then()
.statusCode(200)
.statusLine("HTTP/1.1 200 OK")
.body("data.first_name",hasItems("George","Emma"))
.log().all();
}
}

Q: What are different types of Authorization in Restassured ?

Ans:

Basic Authentication in Rest Assured

As discussed above, the basic authentication scheme uses the username and password in base64 encoded format. The request header needs to contain the credentials of the 
user for access to the resource. It is very easy to send the credentials using the basic auth and you may use the below syntax-

given().auth().basic("your username", "your password").get("your end point URL");
In the given method you need to append the method of authentication specification followed by the basic HTTP auth where you will pass the credentials as the parameters.
 Another type of basic authentication is preemptive which we will discuss next.

package org.example;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.specification.RequestSpecification;

public class BasicAuth {

    @Test
    public void getData() {
       RequestSpecification httpRequest = RestAssured.given().auth().basic("postman", "password"); 
       Response res = httpRequest.get("https://postman-echo.com/basic-auth");
       ResponseBody body = res.body();
       //Converting the response body to string
       String rbdy = body.asString();
       System.out.println("Data from the GET API- "+rbdy);
    }
}

Preemptive Authentication
By default, Rest Assured uses the challenge-response mechanism. This means that it waits for the server to challenge rather than send the credentials directly. 
By using the preemptive directives we can avoid that additional call that the server makes and hence additional complications. In a way, it is similar to the basic 
auth we saw above, the only difference is that an additional premptive () directive adds after auth (). Let us see its syntax followed by a working code example.

given().auth().preemptive().basic("your username", "your password").get("your end point URL");
As you may see above, the preemptive authentication view sends the authentication details in the request header irrespective of being asked by the server. In the 
same line of implementation, we will see a simple API that uses preemptive authentication.

package org.example;
import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.specification.RequestSpecification;

public class BasicAuth {
    @Test
    public void getUserData() {
        //Using the preemptive directive of basic auth to send credentials to the server
        RequestSpecification httpRequest = RestAssured.given().auth().preemptive().basic("postman", "password");
        Response res = httpRequest.get("https://postman-echo.com/basic-auth");
        ResponseBody body = res.body();
        //Converting the response body to string
        String rbdy = body.asString();
        System.out.println("Data from the GET API- "+rbdy);
    }
}
The code example used above is a simple Get API where we are trying to fetch the details corresponding to the user. Note that the server needs the authentication details 
of the user to get a successful response. Let us glide through the code line-by-line.

 RequestSpecification httpRequest =  RestAssured.given().auth().preemptive().basic("postman", "password");
An object of RequestSpecification is created and using the preemptive directive the credentials of the user are sent in the header. Note that irrespective of being asked 
for the credentials these would be passed to the server.

Response res = httpRequest.get("https://postman-echo.com/basic-auth");
ResponseBody body = res.body();
The endpoint URL is accessed using the get method and the response is saved using the ResponseBody object.

String rbdy = body.asString(); 
System.out.println("Data from the GET API- "+rbdy);
Finally, we convert the response body to string and print the result. Similarly, you may add additional validations as per your requirements.

Console prints the response of the above code without errors.

basic_auth_rest_assured_success

And there you go! You have successfully retrieved the user data by simply adding the preemptive authentication in your code and passing the credentials.

Digest Authentication
It is somewhat similar to challenge-based authentication but is more secure as it uses a digestive key in subsequent requests. If at all it is intercepted by an eavesdropper, 
he will get access only to the transaction performed and not the user password. The transaction might be replayed but a new transaction cannot be made as the password is not exposed. 
 Its syntax is similar to basic authentication-

given().auth().digest("your username", "your password").get("your end point URL")
Note that we cannot use the preemptive () similar to basic auth since this scheme uses only challenged authentication.

Form Authentication
There can be many cases when you need to pass the authentication credentials in an HTML form. This request is generally sent as a post method where the credentials entered 
in the form are used for authentication. So, if your application uses such a form-based authentication you can easily automate it using the form() scheme. 
The syntax for it follows-

given ().auth ().digest ("your username", "your password").get ("your endpoint URL")

given() .auth().form("your username", "your password").post("your end point URL")
If you use this approach then Rest Assured will first have to parse through the HTML response to find the fields for input and then send the form parameters. 
However, there is a high possibility that this approach might fail if the webpage is complex. Additionally, it would also fail if the context path is not 
included in the action attribute of the service. To optimize it to handle such cases, you may use the below format where you explicitly pass the required fields by 
providing the FormAuthConfig()-

given().auth().form("your username", "your password", new FormAuthConfig("/perform_signIn","user","password"))

OAuth Authentication
Another type of authentication is OAuth authentication. OAuth is an authorization framework that defines an identity protocol. It has wide usage in web 
applications and there are high chances that you will have to automate those authentication actions. These can be of two types viz, OAuth 1.0 and OAuth 2.0 
which we will discuss now.

OAuth 1.0
Secured resources built using OAuth 1.0 requires passing consumer key, secret, access token, and token secret. The syntax it follows is -

given().auth().oauth(consumerKey, consumerSecret, accessToken, tokenSecret).get("your end point URL")
OAuth parameters read the required user input dynamically.

OAuth 2.0
There are cases when we need to generate an access token for a user session. This access token performs various transactions and helps maintain the user session. While using 
OAuth 2.0 you need to directly pass the access token generated when the user login using the below syntax-

given().auth().oauth2("Access token").get("your end point URL")
Using the access token you can easily request any of the resources secured using the OAuth scheme.

Q: How does Rest Assured work internally?

Ans:
Rest Assured is a library that provides a set of easy-to-use methods for testing RESTful APIs. When a developer writes a test case using Rest Assured, the library uses 
an HTTP client library to send an HTTP request to the API endpoint and receive a response. It then uses a library to deserialize the response data (often in JSON format) 
into Java objects. 
The developer can then use the provided methods to check various aspects of the response, such as the status code, response headers, and response body. 
Rest Assured uses a fluent API design that makes it easy to write test cases in a readable and natural language-like syntax.

Q: Create pojo class for nested json structure

Ans: public class NestedJson { private String name; private int age; private Contact contact; // Getters and Setters
public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Contact getContact() { return contact; } public void setContact(Contact contact) { this.contact = contact; } // Inner class representing the nested 'contact' object public static class Contact
{ private String email; private String phone; // Getters and Setters public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; }
}
===============================================================

1. What is an API?

An API (Application Programming Interface) is a software intermediary that
enables two applications to communicate with each other. It comprises a number
of subroutine definitions, logs, and tools for creating application software.
In an API testing interview, you could be asked to give some API examples, here
are the well-known ones: Google Maps API, Amazon Advertising API, Twitter
API, YouTube API, etc.

2. What are main differences between API and Web Service?

• All Web services are APIs but not all APIs are Web services.
• Web services might not contain all the specifications and cannot perform all the
tasks that APIs would perform.
• A Web service uses only three styles of use: SOAP, REST and XML-RPC for
communication whereas API may be exposed to in multiple ways.
API Testing Interview Questions & Answers
• A Web service always needs a network to operate while APIs don’t need a
network for operation.


3. What are the Limits of API Usage?

Many APIs have a certain limit set up by the provider. Thus, try to estimate your
usage and understand how that will impact the overall cost of the offering.
Whether this will be a problem depends in large part on how data is leveraged.
Getting caught by a quota and effectively cut-off because of budget limitations
will render the service (and any system or process depending on it) virtually
useless.

Creating an API (Common Web API Testing interview
questions)

4. What are some architectural styles for creating a Web API?

This is one of the fundamental Web API interview questions. Bellows are four
common Web API architectural styles:
• HTTP for client-server communication
• XML/JSON as formatting language
• Simple URI as the address for the services
• Stateless communication

5. Who can use a Web API?

Web API can be consumed by any clients which support HTTP verbs such as
GET, PUT, DELETE, POST. Since Web API services do not require
configuration, they can be easily used by any client. In fact, even portable devices
such as mobile devices can easily use Web API, which is undoubtedly the biggest
advantage of this technology.

Testing an API – Top Web API Testing interview questions &
answers

6. What is API Testing?

API testing is a kind of software testing that determines if the developed APIs
meet expectations regarding the functionality, reliability, performance, and
security of the application.


7. What are the advantages of API Testing?

In an API interview, they are likely to ask about the advantages of API testing.
So be prepared with the significant ones such as:
• Test for Core Functionality: API testing provides access to the application
without a user interface. The core and code-level of functionalities of the
application will be tested and evaluated early before the GUI tests. This will help
detect the minor issues which can become bigger during the GUI testing.
• Time Effective: API testing usually is less time consuming than functional GUI
testing. The web elements in GUI testing must be polled, which makes the testing
process slower. Particularly, API test automation requires less code so it can
provide better and faster test coverage compared to GUI test automation. These
will result in the cost saving for the testing project.
• Language-Independent: In API testing, data is exchanged using XML or JSON.
These transfer modes are completely language-independent, allowing users to
select any code language when adopting automation testing services for the
project.
• Easy Integration with GUI: API tests enable highly integrable tests, which is
particularly useful if you want to perform functional GUI tests after API testing.
For instance, simple integration would allow new user accounts to be created
within the application before a GUI test started.

8. Some common protocols used in API testing?

Many protocols are now available to be used in API testing, such as JMS, REST,
HTTP, UDDI and SOAP.

9. What is the test environment of API?

Setting up the API’s test environment is not an easy task, so you should have a
ready answer if your API testing interview is coming. The test environment of
API is a bit complete and requires the configuration of the database and server,
depending on the software requirements. No GUI (Graphical User Interface) is
available in this test form.
When the installation process is complete, API is verified for the proper
operation. Throughout the process, the API called from the original environment
is set up with different parameters to study the test results.

10. What are principles of an API test design?

The five most important principles of an API test design are:
• Setup: Create objects, start services, initialize data, etc
• Execution: Steps to apply API or the scenario, including logging
• Verification: Oracles to evaluate the result of the execution
• Reporting: Pass, failed or blocked
• Clean up: Pre-test state

11. What are the common API testing types?

While there are certainly specialty tests, and no list can be asked to be
comprehensive in this realm, most tests fit broadly into these following nine
categories that you should remember before attending in an API testing interview.
1. Validation Testing
2. Functional Testing
3. UI testing
4. Load testing
5. Runtime/ Error Detection
6. Security testing
7. Penetration testing
8. Fuzz testing
9. Interoperability and WS Compliance testing
12. What is the procedure to perform API testing?
1. Choose the suite to add the API test case
2. Choose the test development mode
3. Demand the development of test cases for the required API methods
4. Configure the control parameters of the application and then test conditions
5. Configure method validation
6. Execute the API test
7. Check test reports and filter API test cases
8. Arrange all API test cases

13. What must be checked when performing API testing?

During the API testing process, a request is raised to the API with the known data.
This way you can analyze the validation response. While testing an API, you
should consider:
• Accuracy of data
• Schema validation
• HTTP status codes
• Data type, validations, order and completeness
• Authorization checks
• Implementation of response timeout
• Error codes in case API returns, and
• Non-functional testing like performance and security testing

14. What is the best approach method to perform API testing?

The following factors should be considered when performing API testing:
• Defining the correct input parameters
• Verifying the calls of the mixture of two or more added value parameters
• Defining the basic functionality and scope of the API program
• Writing appropriate API test cases and making use of testing techniques such as
equivalence class, boundary value, etc. to check the operability
• Testing case execution
• Comparing the test result with the expected result
• Verifying the API behavior under conditions such as connection to files and so
on.

15. What are tools could be used for API testing?

There are myriad of different API testing tools available. A few of common tools
are Katalon Studio, Postman, SoapUi Pro, Apigee, etc. While doing Unit and
API testing, both targets source code. If an API method uses code based in .NET
then another supporting tool must have .NET.

16. What are differences between API Testing and Unit Testing?

API Testing UNIT Testing
Conducted by QA Team Conducted by Development Team
Mostly block box testing White box testing
Aimed to access the full functionality
of the system for it will be employed
by the end users ( external developers
who will use your API)
Used to verify whether each unit in
isolation performs as expected or not.
Often run after the build is ready and
authors do not have access to the
source code.
Each of the code modules must be
ensured to pass the unit test before
being built by developers.

17. What are differences between API Testing and UI Testing?

• API enables communication between two separate software systems. A software
system implementing an API contains functions or subroutines that can be
executed by another software system.
• On the other hand, UI ( User Interface) testing refers to testing graphical interface
such as how users interact with the applications, testing application elements like
fonts, images, layouts etc. UI testing basically focuses on look and feel of an
application.

18. What are major challenges faced in API testing?

If you can overcome the challenges in API Testing, you can be confident in the
API testing interview too. They are:
• Parameter Selection
• Parameter Combination
• Call sequencing
• Output verification and validation
• Another important challenge is providing input values, which is very difficult as
GUI is not available in this case.

19. What are the testing methods that come under API testing?

One of the most common Web API testing interview questions is about the testing
methods. They are:
• Unit testing and Functional testing
• Load testing to test the performance under load
• Discovery testing to list, create and delete the number of calls documented in API
• Usability and Reliability testing to get consistent results
• Security and Penetration testing to validate all types of authentication
• Automation testing to create and run scripts that require regular API calls
• End to end Integration and Web UI testing
• API documentation testing to determine its efficiency and effectiveness

20. Why is API testing considered as the most suitable form for Automation
testing?

API testing is now preferred over GUI testing and is considered as most suitable
because:
• It verifies all the functional paths of the system under test very effectively.
• It provides the most stable interface.
• It is easier to maintain and provides fast feedback.

21. What are common API errors that often founded?

Not only API fundamental questions, the interviewer also determine your
knowledge and experience by asking about the API errors in a Web API testing
interview. So the most common ones are:
• Missing module errors
• Documentation errors
• Parameter validation errors
• And some standard error expectations as if the result is not so predicted then the
occurrence of errors can be seen and for the same warnings are specified in the
form of a message. There can be one or more warnings within an individual
module.

22. What kinds of bugs that API testing would often find?

• Missing or duplicate functionality
• Fails to handle error conditions gracefully
• Stress
• Reliability
• Security
• Unused flags
• Not implemented errors
• Inconsistent error handling
• Performance
• Multi-threading issues
• Improper errors

Documenting the API (Common Web API Testing interview
questions)

23. What is API documentation?

The API documentation is a complete, accurate technical writing giving
instructions on how to effectively use and integrate with an API. It is a compact
reference manual that has all the information needed to work with the API, and
helps you answer all the API testing questions with details on functions, classes,
return types, arguments, and also examples and tutorials.

24. What are API documentation templates that are commonly used?

There are several available API documentation templates help to make the entire
process simple and straightforward, which could be answered in your API testing
interview, such as:
• Swagger
• Miredot
• Slate
• FlatDoc
• API blueprint
• RestDoc
• Web service API specification

25. When writing API document, what must be considered?

• Source of the content
• Document plan or sketch
• Delivery layout
• Information needed for every function in the document
• Automatic document creation programs

26. How often are the APIs changed and, more importantly, deprecated?

APIs, especially modern RESTful APIs, are a nice creation that can certainly
simplify and accelerate integration efforts, which makes it more likely you will
benefit from them. But APIs can and do change for various reasons, sometimes
abruptly, and hence REST APIs do not differ from traditional integration methods
in this respect. If an API call is obsolete and disappears, your procedure will
interrupt and it is important to understand how often the APIs you depend on
change or are deprecated.

REST (Common Web API Testing interview questions)

27. 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, a REST Server provides access to resources and REST
client accesses and makes these resources available. Here, each resource is
identified by URIs or global IDs, and REST uses multiple ways to represent a
resource, such as text, JSON, and XML. XML and JSON are nowadays the most
popular representations of resources.

28. What is a RESTFul Web Services?

Mostly, there are two kinds of Web Services which should be remembered in your
next API testing interview:
1. SOAP (Simple Object Access Protocol) – an XML-based method to expose
web services.
2. Web services developed in the REST style are referred to as RESTful web
services. These web services use HTTP methods to implement the concept
of REST architecture. A RESTful web service usually defines a URI,
Uniform Resource Identifier a service, provides resource representation
like JSON and a set of HTTP methods.

29. What is a “Resource” in REST?

REST architecture treats any content as a resource, which can be either text files,
HTML pages, images, videos or dynamic business information.
REST Server gives access to resources and modifies them, where each resource
is identified by URIs/ global IDs.
30. What is the most popular way to represent a resource in REST?
REST uses different representations to define a resource like text, JSON, and
XML.
XML and JSON are the most popular representations of resources.

31. Which protocol is used by RESTful Web services?

RESTful web services use the HTTP protocol as a medium of communication
between the client and the server.

32. What are some key characteristics of REST?

Key characteristics of REST are likely asked in a Web API Testing interview. So
please get the answer ready in your mind with these 2 ones:
• REST is stateless, therefore the SERVER has no status (or session data)
With a well-applied REST API, the server could be restarted between two calls,
since all data is transferred to the server
• Web service uses POST method primarily to perform operations, while REST
uses GET for accessing resources.

33. What is messaging in RESTful Web services?

RESTful web services use the HTTP protocol as a communication tool between
the client and the server. The technique that when the client sends a message in
the form of an HTTP Request, the server sends back the HTTP reply is called
Messaging. These messages comprise message data and metadata, that is,
information on the message itself.

34. What are the core components of an HTTP request?

An HTTP request contains five key elements:
1. An action showing HTTP methods like GET, PUT, POST, DELETE.
2. Uniform Resource Identifier (URI), which is the identifier for the resource
on the server.
3. HTTP Version, which indicates HTTP version, for example-HTTP v1.1.
4. Request Header, which carries metadata (as key-value pairs) for the HTTP
Request message. Metadata could be a client (or browser) type, format
supported by the client, format of a message body format, cache settings,
and so on.
5. Request Body, which indicates the message content or resource
representation.

35. What are the most commonly used HTTP methods supported by REST?

• GET is only used to request data from a specified resource. Get requests can be
cached and bookmarked. It remains in the browser history and haS length
restrictions. GET requests should never be used when dealing with sensitive data.
• POST is used to send data to a server to create/update a resource. POST requests
are never cached and bookmarked and do not remain in the browser history.
• PUT replaces all current representations of the target resource with the request
payload.
• DELETE removes the specified resource.
• OPTIONS is used to describe the communication options for the target resource.
• HEAD asks for a response identical to that of a GET request, but without the
response body.

36. Can GET request to be used instead of PUT to create a resource?

The PUT or POST method should be used to create a resource. GET is only used
to request data from a specified resource.

37. Is there any difference between PUT and POST operations?

PUT and POST operation are quite similar, except the terms of the result
generated by them.
PUT operation is idempotent, so you can cache the response while the responses
to POST operation are not cacheable, and if you retry the request N times, you
will end up having N resources with N different URIs created on server.
In a Web API Testing interview, you should give a specific example for PUT and
POST operations to make crystal clear to the interviewer. Below is an example:
Scenario: Let’s say we are designing a network application. Let’s list down few
URIs and their purpose to get to know when to use POST and when to use PUT
operations.
GET /device-management/devices : Get all devices
POST /device-management/devices : Create a new device
GET /device-management/devices/{id} : Get the device information identified by
“id”
PUT /device-management/devices/{id} : Update the device information
identified by “id”
DELETE /device-management/devices/{id} : Delete device by “id”

38. Which purpose does the OPTIONS method serve for the RESTful Web
services?

The OPTIONS Method lists down all the operations of a web service supports. It
creates read-only requests to the server.

39. What is URI? What is the main purpose of REST-based web services and
what is its format?

URI stands for Uniform Resource Identifier. It is a string of characters designed
for unambiguous identification of resources and extensibility via the URI scheme.
The purpose of a URI is to locate a resource(s) on the server hosting of the web
service.
A URI’s format is <protocol>://<servicename>/<ResourceType>/<ResourceID>.

40. What is payload in RESTFul Web services?

The “payload” is the data you are interested in transporting. This is differentiated
from the things that wrap the data for transport like the HTTP/S
Request/Response headers, authentication, etc.

41. What is the upper limit for a payload to pass in the POST method?

<GET> appends data to the service URL. But, its size shouldn’t exceed the
maximum URL length. However, <POST> doesn’t have any such limit.
So, theoretically, a user can pass unlimited data as the payload to POST method.
But, if we consider a real use case, then sending POST with large payload will
consume more bandwidth. It’ll take more time and present performance
challenges to your server. Hence, a user should take action accordingly.

42. What is the caching mechanism?

Caching is just the practice of storing data in temporarily and retrieving data from
a high-performance store (usually memory) either explicitly or implicitly.
When a caching mechanism is in place, it helps improve delivery speed by storing
a copy of the asset you requested and later accessing the cached copy instead of
the original.

SOAP (Common Web API Testing interview questions)

43. What are SOAP Web services?

This is one of the fundamental Web services testing questions that you must know
the answer. The SOAP (Simple Object Access Protocol) is defined as an XMLbased protocol. It is known for designing and developing web services as well as
enabling communication between applications developed on different platforms
using various programming languages over the Internet. It is both platform and
language independent.

44. How does SOAP work?

SOAP is used to provide a user interface that can be accessed by the client object,
and the request that it sends goes to the server, which can be accessed using the
server object. The user interface creates some files or methods consisting of server
object and the name of the interface to the server object. It also contains other
information such as the name of the interface and methods. It uses HTTP to send
the XML to the server using the POST method, which analyzes the method and
sends the result to the client. The server creates more XML consisting of
responses to the request of user interface using HTTP. The client can use any
approach to send the XML, like the SMTP server or POP3 protocol to pass the
messages or reply to queries.

45. When to use SOAP API?

Use the SOAP API to create, retrieve, update or delete records, like accounts,
leads, and user-defined objects. With more than 20 different calls, you can also
use the SOAP API to manage passwords, perform searches, etc. by using the
SOAP API in any language that supports web services.

46. How users utilize the facilities provided by SOAP?

• PutAddress(): It is used to enter an address in the webpage and has an address
instance on the SOAP call.
• PutListing(): It is used to allow the insertion of a complete XML document into
the web page. It receives the XML file as an argument and transports the XML
file to XML parser liaison, which reads it and inserts it into the SOAP call as a
parameter.
• GetAddress(): It is used to get a query name and gets the result that best matches
a query. The name is sent to the SOAP call in the form of text character string.
• GetAllListing(): It is used to return the full list in an XML format.

47. What is the major obstacle users faced when using SOAP?

When using SOAP, users often see the firewall security mechanism as the biggest
obstacle. This block all the ports leaving few like HTTP port 80 and the HTTP
port used by SOAP that bypasses the firewall. The technical complaint against
SOAP is that it mixes the specification for message transport with the
specification for message structure.

48. What are the various approaches available for developing SOAP
based web services?

There are two different methods available for developing SOAP-based web
services, which are explained below:
• Contract-first approach: the contract is first defined by XML and WSDL, and then
Java classes are derived from the contract.
• Contract-last approach: Java classes are first defined, and then the contract is
generated, which is normally the WSDL file from the Java class.
“Contract-first” method is the most popular approach.

49. What are the elements of a SOAP message structure?

It is a common XML document that contains the elements as a SOAP message
Envelope: It is an obligatory root element that translates the XML document and
defines the beginning and end of the message.
Header: It is an optional item which contains information about the message being
sent.
Body: It contains the XML data comprising the message being sent.
Fault: It provides the information on errors that occurred while during message
processing.

50. What are the syntax rules for a SOAP message?

• Must use encoded XML
• Envelope namespace must be used
• Encoding namespace must be used
• Must not consist of a DTD reference
• Must not have XML processing instruction

51. What is the transport method in SOAP?

Application layer and transport layers of a network are used by SOAP; HTTP and
SMTP are the valid protocol of the application layer used as the transport for
SOAP. HTTP is more preferable, since it works well with the current Internet
infrastructure, in particular with firewalls.
The SOAP requests can be sent using an HTTP GET method while the
specification only contains details about HTTP POST.

52. What are some important characteristics of a SOAP envelope element?

• SOAP message has a root Envelope element
• Envelope is an obligatory part of the SOAP message.
• If an envelope includes a header element, it should not contain more than one.
• Envelope version will change if the SOAP version changes.
• The SOAP envelope is indicated by the prefix ENV and the envelope element.
• The optional SOAP encoding is also specified using a namespace and the optional
encoding style element.


53. What are the major functionalities provided by the SOAP protocol class?

The SOAP protocol is used to provide simple access methods for all the
applications available on the Internet, providing the following functionalities:
• Call: A class which provides the main functionality for a remote method for
which a call is needed. It is used to create the call() and to specify the encoding
style of the registry that will be assigned when if necessary. This call() function
is used by the RPC call, which represents the options of the call object.
• Deployment Descriptor: A class used to provide the information about the SOAP
services. It enables easy deployment without the need for other approaches.
• DOM2 Writer: A class that serializes and uses DOM node as XML string to
provide more functionalities.
• RPC Message: A class used as the base class that calls and replies to the request
submitted to the server.
• Service Manager: A class that provides, lists and then outputs all SOAP services.

54. What are the web relation functionalities provided by SOAP protocol?

• HTTPUtils: This provides the functionality of the POST method to safely meet
the requirements.
• Parameter: It is an argument for an RPC call used by both the client and the
server.
• Response: It is an object that represents an RPC reply from both client and server,
but the result will not be displayed until after the method call.
• TCPTunnel: It is an object that provides the ability to listen on a specific port and
to forward all the host and port names.
• TypeConverter: It helps to convert an object of one type into another type and
this is called using the class in the form object.

55. How does the message security model allow the creation of SOAP more
secure to use?

The security model includes the given security tokens. These tokens comprise
digital signatures for protection and authentication of SOAP messages. Security
tokens can be used to provide the bond between authentication secrets or keys
and security identities. Security token uses the authentication protocols and an
X.509 certificate to define the relationship between the public key and identity
key. The signatures are used to verify the messages and their origin, generate
knowledge to confirm the security tokens to bind the identity of a person to the
identity of the originator. Security model prevents different attacks and can be
used to protect the SOAP architecture.

56. What is the difference between top down & bottom up approach in SOAP
Web services?

• Top down SOAP Web services include creating WSDL document to create a
contract between the web service and the client, with a required code as an option.
This is also known as Contract-first approach. The top-down approach is difficult
to implement because classes must be written to confirm the contract defined in
WSDL. One of the benefits of this method is that both client and server code can
be written in parallel.
• Bottom up SOAP web services require the code to be written first and then WSDL
is generated. It is also known as Contract-last approach. Since WSDL is created
based on the code, bottom-up approach is easy to implement and client codes
must wait for WSDL from the server side to start working.

57. What are advantages of SOAP?

• SOAP is both platform and language independent.
• SOAP separates the encoding and communications protocol from the runtime
environment.
• Web service can retrieve or receive a SOAP user data from a remote service, and
the source’s platform information is completely independent of each other.
• Everything can generate XML, from Perl scripts through C++ code to J2EE app
servers.
• It uses XML to send and receive messages.
• It uses standard internet HTTP protocol.
• SOAP runs over HTTP; it eliminates firewall problems. When protocol HTTP is
used as the protocol binding, an RPC call will be automatically assigned to an
HTTP request, and the RPC response will be assigned to an HTTP reply.
• Compared to RMI, CORBA and DCOM, SOAP is very easy to use.
• SOAP acts as a protocol to move information in a distributed and decentralized
environment.
• SOAP is independent of the transport protocol and can be used to coordinate
different protocols.

58. What are disadvantages of SOAP?

SOAP is typically significantly slower than other types of middleware standards,
including CORBA, because SOAP uses a detailed XML format. A complete
understanding of the performance limitations before building applications around
SOAP is hence required.
SOAP is usually limited to pooling and not to event notifications when HTTP is
used for the transport. In addition, only one client can use the services of one
server in typical situations.
If HTTP is used as the transport protocol, firewall latency usually occurs since
the firewall analyzes the HTTP transport. This is because HTTP is also leveraged
for Web browsing, and so many firewalls do not understand the difference
between using HTTP within a web browser and using HTTP within SOAP.
SOAP has different support levels, depending on the supported programming
language. For instance, SOAP supported in Python and PHP is not as powerful as
it is in Java and .NET

59. SOAP or Rest APIs, which method to use?

SOAP is the heavyweight choice for Web service access. It provides the following
advantages when compared to REST:
• SOAP is not very easy to implement and requires more bandwidth and resources.
• SOAP message request is processed slower as compared to REST and it does not
use web caching mechanism.
• WS-Security: While SOAP supports SSL (just like REST) it also supports WSSecurity which adds some enterprise security features.
• WS-AtomicTransaction: Need ACID Transactions over a service, you’re going
to need SOAP.
• WS-ReliableMessaging: If your application needs Asynchronous processing and
a guaranteed level of reliability and security. Rest doesn’t have a standard
messaging system and expects clients to deal with communication failures by
retrying.
• If the security is a major concern and the resources are not limited then we should
use SOAP web services. Like if we are creating a web service for payment
gateways, financial and telecommunication related work, then we should go with
SOAP as here high security is needed.
REST is easier to use for the most part and is more flexible. It has the following
advantages when compared to SOAP:
• Since REST uses standard HTTP, it is much simpler.
• REST is easier to implement, requires less bandwidth and resources.
• REST permits many different data formats whereas SOAP only permits XML.
• REST allows better support for browser clients due to its support for JSON.
• REST has better performance and scalability. REST reads can be cached, SOAP
based reads cannot be cached.
• If security is not a major concern and we have limited resources. Or we want to
create an API that will be easily used by other developers publicly then we should
go with REST.
• If we need Stateless CRUD operations then go with REST.
• REST is commonly used in social media, web chat, mobile services and Public
APIs like Google Maps.
• RESTful service returns various MediaTypes for the same resource, depending
on the request header parameter “Accept” as application/xml or application/json
for POST and /user/1234.json or GET /user/1234.xml for GET.
• REST services are meant to be called by the client-side application and not the
end user directly.
• ST in REST comes from State Transfer. You transfer the state around instead of
having the server store it, this makes REST services scalable.

60. What are the factors that help to decide which style of Web services –
SOAP or REST – to use?

Generally, REST is preferred due to its simplicity, performance, scalability, and
support for multiple data formats.
However, SOAP is favorable to use where service requires an advanced level of
security and transactional reliability.
But you can read the following facts before opting for any of the styles.
• Does the service expose data or business logic? REST is commonly used for
exposing data while SOAP for logic.
• The requirement from clients or providers for a formal contract. SOAP can
provide contract via WSDL.
• Support multiple data formats.
• Support for AJAX calls. REST can apply the XMLHttpRequest.
• Synchronous and asynchronous calls. SOAP enables both synchronous/
asynchronous operations whereas REST has built-in support for synchronous.
• Stateless or Stateful calls. REST is suited for stateless operations.
• Security. SOAP provides a high level of security.
• Transaction support. SOAP is good at transaction management.
• Limited bandwidth. SOAP has a lot of overhead when sending/receiving packets
since it’s XML based, requires a SOAP header. However, REST requires less
bandwidth to send requests to the server. Its messages are mostly built using
JSON.
• Ease of use. REST based application is easy to implement, test, and maintain.


Comments