Thursday 21 March 2024

API Interview Preparation

 
1. What are the main differences between API and Web Service?
  • All Web services are APIs but not all APIs are Web services.
  • Web service uses three styles of use: SOAP, REST and XML-RPC for communication whereas   API  may be exposed in multiple ways.
  • Web service needs a network to operate but APIs don’t need a network to operate.

2. What is REST?

  • REST (Representational State Transfer) is an architectural style for developing web services which exploit the ubiquity of HTTP protocol and uses HTTP method to define actions. It revolves around resource where every component being a resource that can be accessed through a shared interface using standard HTTP methods.
  • In REST architecture, REST Server provides access to resources and client accesses and makes these resources available.
  • Each resource is identified by URIs or global IDs, and REST uses multiple ways to represent a resource, such as text, JSON, and XML.

3. Explain what statelessness means in REST?

Statelessness means that the client and server don’t store information about each other’s state. 
Since the server stores no information, it treats each client request as a new request.
As a consequence, the following conditions would apply:
  • The client request contains all information required for the server to process the request
  • Client application is responsible for storing session state

Path param vs Query param vs Form param

In RESTful API, there are three common ways to pass data between the client and server: path parameter, query parameter, and form parameter. 
 

Here's an example of how to use each parameter type with RestAssured in Java:

Path parameter 

Path parameters are used to identify a specific resource in the URL path. They are specified in the URL path and preceded by a colon (:). In RestAssured, we can pass path parameters using the pathParam() method. 

EXAMPLE

Suppose we have a RESTful API endpoint that retrieves a user's information based on their ID, which is passed as a path parameter:
GET /users/:id

CODE with Rest Assured:

To pass the path parameter using RestAssured, we can use the pathParam() method like this:
int userId = 123;
given()
    .pathParam("id", userId)
.when()
    .get("/users/{id}")
.then()
    .statusCode(200);

Query parameter

Query parameters are used to filter or sort data. They are specified in the URL query string and separated by an ampersand (&). In RestAssured, we can pass query parameters using the queryParam() method. 

EXAMPLE 

Suppose we have a RESTful API endpoint that retrieves a list of users based on their gender, which is passed as a query parameter:
GET /users?gender=female

CODE with Rest Assured

To pass the query parameter using RestAssured, we can use the queryParam() method like this:
given()
    .queryParam("gender", "female")
.when()
    .get("/users")
.then()
    .statusCode(200);

Form parameter

Form parameters are used to submit data to the server in an HTTP form. They are specified in the request body as key-value pairs. In RestAssured, we can pass form parameters using the formParam() method. 

EXAMPLE

Suppose we have a RESTful API endpoint that creates a new user based on their name and email, which are passed as form parameters:
POST /users
Content-Type: application/x-www-form-urlencoded
name=Sidharth&email=sidharth@gmail.com

CODE with Rest Assured

To pass the form parameters using RestAssured, we can use the formParam() method like this:
given()
    .formParam("name", "Sidharth")
    .formParam("email", "sidharth@gmail.com")
.when()
    .post("/users")
.then()
    .statusCode(201);
    
    
4. What is Schema?

Schema is nothing but a JSON file. It will only have datatype information and the expected keys of the JSON. There won't be any values present in the schema. 
Schema is an important concept to learn. JSON Schema is a JSON media type for defining the structure of JSON data. JSON Schema provides a contract for what JSON data is required for a given application and how to interact with it. JSON Schema is intended to define validation, documentation, hyperlink navigation, and interaction control of JSON data.

5. Why JSON Schema Validation is required? 

JSON Schema Validation is required to monitor API responses and ensure that the format that we are getting is the same as the expected one.

Error:(common errors in your current project)
object has missing required properties, instance type (integer) does not match any allowed primitive type (allowed: ["string"])

6. What are the disadvantages of REST API?

  • Doesn’t enforce security practices
  • HTTP method limits you to synchronous requests
  • Due to statelessness, you might be unable to maintain state (e.g. in sessions)

7. 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
 8. 
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.

9. What are the types of methods most used in RestAPI Testing?

GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS
P1 : GET POST DELETE
P2 : PUT
P3 : PATCH

10. What are the types of Status codes?

  • 1xx informational response – the request was received, continuing process
  • 2xx successful – the request was successfully received, understood, and accepted
  • 3xx redirection – further action needs to be taken in order to complete the request
  • 4xx client error – the request contains bad syntax or cannot be fulfilled
  • 5xx server error – the server failed to fulfil an apparently valid request
  • 200:  OK
  • 201:  Created
  • 204:  No Content
  • 400:  Bad Request
  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not Found
  • 302: Redirect
  • 405: Method Not Allowed
  • 422: Unprocessable Entity
  • 417: Expectation failed
  • 500: Internal Server Error
11. How well do you know APIs? 

Let's delve into the 4 Components of a REST API! 
1. API client
2. API request
3. API server
4. API response

API client : The API client is the software or application that initiates requests to the API server to retrieve or manipulate data. 

It acts as an intermediary between the end-user or application and the API server. 
The API client is responsible for sending properly formatted requests to the server and handling the responses received.

Example: 
Let's say you have a mobile application that displays weather information for a user's location. 
The mobile app acts as the API client in this scenario. 
When the user opens the app, it sends a request to the weather API server to fetch the current weather data for the user's location.

API request:
The API request is a message sent by the API client to the API server, indicating the action it wants to perform. 
This request contains information such as the specific API endpoint (URL), request method (GET, POST, PUT, DELETE, etc.), headers, and sometimes data (e.g., in the case of a POST request).

Example: 
In the weather app example, the API request might be a GET request to the weather API server with the endpoint like "https://lnkd.in/g6f6fXVj" to get the current weather data for the user's location.

API server:

The API server is a software application that receives API requests from clients, processes those requests, interacts with the database or other services as needed, and generates a response back to the API client. 
It acts as the gateway to the backend system, providing access to the requested resources.

Example: 
The weather API server receives the GET request from the mobile app's API client, processes the request, queries the weather data for the user's location from its database or external services, and then generates a response containing the weather information.

API response:
The API response is the message sent by the API server to the API client in reply to the API request. 
It contains the data requested by the client, along with any relevant metadata or status codes to indicate the success or failure of the request.

Example: 
After processing the GET request from the weather app's API client, the API server generates an API response containing the current weather data for the user's location, such as temperature, humidity, and weather conditions. 
This response is then sent back to the API client (mobile app), which can then display the weather information to the user.

8. What is HEAD method?

The HEAD method asks for a response identical to that of a GET request, but without the response body.
This is useful for retrieving meta-information written in response headers, without having to transport the entire content

9. What is OPTIONS method?
The OPTIONS method returns the HTTP methods that the server supports for the specified URL.


 PUT is Idempotent, POST is not Idempotent.

PUT is Idempotent: This means that performing the same PUT request multiple times will have the same effect as performing it once. In other words, if you send the same data with a PUT request repeatedly, it will result in the same resource state on the server. This property is useful for ensuring consistency and predictability in API interactions.

POST is not Idempotent: This means that performing the same POST request multiple times might result in different outcomes or states on the server. Each POST request typically creates a new resource on the server or performs a non-idempotent action, such as updating a resource with different data each time. POST requests are commonly used for creating new resources, submitting form data, or triggering actions that are not idempotent.

In summary, the distinction lies in the behavior of these HTTP methods when invoked repeatedly: PUT requests produce the same result each time (idempotent), while POST requests might not (non-idempotent).

 Http vs HTTPS

 In HTTP, URL begins with “http://” whereas URL starts with “https://”
1. HTTP uses port number 80 for communication and HTTPS uses 443
2. HTTP is considered to be unsecured and HTTPS is secured
3. HTTP Works at Application Layer and HTTPS works at Transport Layer
4. In HTTP, Encryption is absent and Encryption is present in HTTPS 
5. HTTP does not require any certificates and HTTPS needs SSL Certificates

 Automate GET method and validate the status code?

@Test(description="Verify status code for GET method-users/2 as 200")
 public static void verifyStatusCodeGET() {
  Response resp = given()
                              .when()
          .get("https://reqres.in/api/users/2");
assertEquals(resp.getStatusCode(),200);
 }
 
 
 Automate GET method and fetch response body?
  
  @Test(description="Verify status code for GET method-users/2 as 200")
  public static void verifyStatusCodeGET() {
  Response resp= given()
  .when().get("https://reqres.in/api/users/2");
  assertEquals(resp.getBody().asString(),200);
   
  }
  
 Automate GET method and verify value from response body?(validate that total number pages =12)

@Test(description="Verify status code for GET method-users/2 as 200")
public static void verifyStatusCodeGET() {
Response resp = given()
.when().get("https://reqres.in/api/users");
System.out.println(resp.path("total").toString());
assertEquals(resp.getStatusCode(),200);
assertEquals(resp.path("total").toString(),"12");
}

How to pass query param with GET method in Rest Assured?

API Query parameters can be defined as the optional key-value pairs that appear after the question mark in the URL. Basically, they are extensions of the URL that are utilized to help determine specific content or action based on the data being delivered. Query parameters are appended to the end of the URL, using a '?

@Test
public void validateQueryParamInGiven() {
  Response resp = given().queryParam("page", "2").
when().get("https://reqres.in/api/users");
assertEquals(resp.getStatusCode(),200);
System.out.println(resp.getBody().asString());
}


How to pass header for GET method in Rest Assured?

@Test
public void validateGivenHeader() {
  
  Response resp = given()
  .header("Content-Type", "application/json").
when()
.get("https://gorest.co.in/public-api/users");
assertEquals(resp.getStatusCode(),200);
System.out.println(resp.getBody().asString());
}

How to automate PATCH method in rest Assured?

The HTTP PATCH method can be used when a resource needs to be updated. This method is especially useful if a resource is large and the changes being made are small.
@Test(description="validate with jsonpath and json object and pass post body as json file")
public void MethodValidationPUT() throws IOException, ParseException {
  
  FileInputStream file = new FileInputStream(new File (System.getProperty("user.dir")+"\\TestData\\put.json"));
Response resp =
given()
.header("Content-Type" , "application/json")
.body(IOUtils.toString(file,"UTF-8")).
        when()
        .patch("https://reqres.in/api/users/2");
assertEquals(resp.getStatusCode(),200);
assertEquals(resp.path("job"),"tester");

17. How to automate PUT method in Rest Assured?

A PUT method puts or places a file or resource precisely at a specific URI. In case a file or a resource already exists at that URI, the PUT method replaces that file or resource. If there is no file or resource, PUT creates a new one.

@Test(description="validate with jsonpath and json object and pass post body as json file")
public void MethodValidationPUT() throws IOException, ParseException {
  
  FileInputStream file = new FileInputStream(new File (System.getProperty("user.dir")+"\\TestData\\put.json"));
Response resp =
given()
.header("Content-Type" , "application/json").body(IOUtils.toString(file,"UTF-8")).
        when()
        .put("https://reqres.in/api/users/2");
assertEquals(resp.getStatusCode(),200);
assertEquals(resp.path("job"),"tester");
  }


18. How to automate POST method in Rest Assured?

 POST requests are used to send data to the API server to create or update a resource. The data sent to the server is stored in the request body of the HTTP request

@Test(description="validate with jsonpath and json object and pass post body as json file")
public void MethodValidationPOST() throws IOException, ParseException {
  
  FileInputStream file = new FileInputStream(new File (System.getProperty("user.dir")+"\\TestData\\put.json"));
Response resp =
given().header("Content-Type" , "application/json").body(IOUtils.toString(file,"UTF-8")).
        when().post("https://reqres.in/api/users");
assertEquals(resp.getStatusCode(),201);
assertEquals(resp.path("job"),"tester");
 
  }
 

How to validate Query Parameters in API Testing?

A valuable question came my way recently: "How to validate Query Parameters in API Testing?"   - Let's dive into it together because I believe this can benefit our fellow testers during API testing! ??
  - Query parameters are the key-value pairs nestled within the URL that clients employ to convey data to your API. 
  - Query parameters consists of key-value pairs appended to the end of a URL, separated by a question mark (?) and ampersands (&) for multiple parameters. 
  - For instance, in a URL like https : //reqres . com/products?category=electronics&price=500, 'category' and 'price' are your query parameters.
  - Lets understand what to consider, For instance, you might insist that 'category' must be a string, and 'price' must be a positive number.
  - For each parameter, put those validation rules you just drafted into action. Here are some common checks to perform:
 - Presence Check: Ensure that those mandatory parameters are indeed present in the request.
  - Type Check: Make sure the parameter's type aligns perfectly with your expectations (e.g., a number must genuinely be a number).
- Range or Format Check: If it's applicable, scrutinize whether the value snugly fits within an acceptable range or adheres to a specific format.
 
 - Very Important Note:
If any parameter fails the validation exam, don't hesitate to respond with an error message that spells out the glitch. For example, if 'price' decides to go negative, your response could be as clear as day: "Price must be a positive number." 

What is the major drawback of using SOAP?

Ans: When using SOAP, users often get 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.

When to use contract testing?

Ans: Contract testing is immediately applicable anywhere where you have two services that you need to communicate - such as an API client and a web front-end. Although a single client and a single service is a common use case, contract testing really shines in an environment with many services (as is common for a microservice architecture). Having well-formed contract tests makes it easy for developers to avoid version hell. Contract testing is a killer app for microservice development and deployment.


Get the same user and verify it: GET
given()
.header("Authorization", "Bearer e4b8e1f593dc4a731a153c5ec8cc9b8bbb583ae964ce650a741113091b4e2ac6")
.when().log().all()
.get("/public/v2/users/"+ userId)
.then()
.assertThat()
.statusCode(200)
.and()
.body("id", equalTo(userId))
.and()
.body("name", equalTo(user.getName()))
.and()
.body("status", equalTo(user.getStatus()))
.and()
.body("email",equalTo(user.getEmail()));



public void addUserTest() {
RestAssured.baseURI = "https://gorest.co.in";
//1. add user - POST
int userId = given().log().all()
.contentType(ContentType.JSON)
.body(new File("./src/test/resources/data/adduser.json"))
.header("Authorization", "Bearer e4b8e1f593dc4a731a153c5ec8cc9b8bbb583ae964ce650a741113091b4e2ac6").
when()
.post("/public/v2/users/").
then().log().all()
.assertThat()
.statusCode(201)
.and()
.body("name", equalTo("naveen"))
.extract()
.path("id");
System.out.println("user id -->" + userId);
//2. get the same user and verify it: GET
given()
.header("Authorization", "Bearer e4b8e1f593dc4a731a153c5ec8cc9b8bbb583ae964ce650a741113091b4e2ac6")
.when().log().all()
.get("/public/v2/users/"+ userId)
.then()
.assertThat()
.statusCode(200)
.and()
.body("id", equalTo(userId));
#APITesting  #QualityAssurance  #testautomation  #testing #automation #softwaretesting #qa #api #software


 
 
















No comments:

Salesforce AI Associate Certification - 3

What is semantic retrieval in the context of LLMs?   Searching for relevant information in other data sources What additional protection do...