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

Saturday, April 17, 2021

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




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

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


Getting Started:

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

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

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

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

json-server --watch db.json

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

Saturday, January 30, 2021

Latest top 10 API Automation Interview Questions and Answer Set 4

 






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


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

Method-1 

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


Method- 2


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



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

public void getWeatherDetailsWithCorrectCityNameTest(String users){

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

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

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

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

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

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

Assert.assertEquals(statusCode, 200);

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

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

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

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



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

public class PostAPI {

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


Method 2

public class PostAPI {

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


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

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

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



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



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

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



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


@Test
public void ValidateJsonSchema()

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



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

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

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


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


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

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


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

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

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


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


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

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

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


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

  @Test
public void validateHeader() {

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

}


To Validate the header:

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

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


16. How to handle Basic Authentication with Rest Assured?

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

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

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

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

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


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

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

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

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


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


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

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

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



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


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

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

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





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

Disadvantages of Rest assured:-

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

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

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

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



public class POSTAPI_getAccessToken {

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

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

static String accessToken = "";

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

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

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

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

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


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

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

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


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

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


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




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

public class ParseDynamicJson {

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

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

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

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

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

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

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

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

}

}

} catch (Exception e) {
}

}

} else {
parseObject(json, key);
}

}

public static void main(String[] args) {

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

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

getKey(inputJSONOBject, "job");

}

}

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


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


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


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

We can do it by using JsonPath class .

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

 OR

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

Sunday, October 18, 2020

Latest top 10 API Interview Questions and Answer Set 3

1. Difference Between PUT and Patch 
Both are used for updating a resource on the server. 
PUT: Replaces the whole object 
PATCH: Replaces a particular field of an object  


2. What is JSON Schema
It is document/Structure or Format that is used to validate Formatting Syntax, Data types, Structure & Content of JSON message. It can be used to validate JSON message also.

To validate API request and Response in JSON format

 JSON schema built on the top of processing of API request to validate input API request before proceeding.



3. Explain process of pushing the code and creating a pull request in GIT. 
a) git clone “repo-url” 

b) make changes to the code. 

c) git add . //add those changes(or staging) 

d) git status //to check changes moved to staging

e) git commit -m”commit message” 

f) git push 

----

g) git checkout -b “branch-name” //for creating a branch 

h) git branch //check if branch created or available branches

i) git checkout “branch name” //Switch to branch

 Here you successfully switch to branch. Now you can push your code by “git push”

 

 3. Difference b/w http and https

  • HTTP URL in your browser’s address bar is http:// and the HTTPS URL is https://.
  • HTTP is unsecured while HTTPS is secured.
  • HTTP sends data over port 80 while HTTPS uses port 443.
  • HTTP operates at application layer, while HTTPS operates at transport layer.
  • No SSL certificates are required for HTTP, with HTTPS it is required that you have an SSL certificate and it is signed by a CA.
  • HTTP doesn’t require domain validation, where as HTTPS requires at least domain validation and certain certificates even require legal document validation.
  • No encryption in HTTP, with HTTPS the data is encrypted before sending.



4. Most Used Authentication Methods

• Basic

• API Key

• Bearer

• OAuth

• Cookie bases Authentication


    Basic Authentication
            This is the most straightforward method and the easiest. With this method, the sender places a username: password into the request header. The username and password are encoded with Base64, which is an encoding technique that converts the username and password into a set of 64 characters to ensure safe transmission.


    API Key:

Some APIs use API keys for authorization. An API key is a token that a client provides when making API calls. The key can be sent in the query string: or as a request header, or as a cookie:
API keys are supposed to be a secret that only the client and server know. Like Basic authentication, API key-based authentication is only considered secure if used together with other security mechanisms such as HTTPS/SSL.


    Bearer Authentication:
Bearer authentication (also called token authentication) is an HTTP authentication scheme that involves security tokens called bearer tokens.
The name “Bearer authentication” can be understood as “give access to the bearer of this token.” The bearer token allowing access to a certain resource or URL and most likely is a cryptic string, usually generated by the server in response to a login request.
The client must send this token in the Authorization header when making requests to protected resources:
Authorization: Bearer <token>


    OAuth (2.0):
The previous versions of this spec, OAuth 1.0 and 1.0a, were much more complicated than OAuth 2.0. The biggest change in the latest version is that it is no longer required to sign each call with a keyed hash. The most common implementations of OAuth use one or both of these tokens instead:
• access token: sent like an API key, it allows the application to access a user’s data; optionally, access tokens can expire.
• refresh token: optionally part of an OAuth flow; refresh tokens retrieve a new access token if they have expired. OAuth2 combines Authentication and Authorization to allow more sophisticated scope and validity control.

OAuth 2.0 is the best choice for identifying personal user accounts and granting proper permissions. In this method, the user logs into a system. That system will then request authentication, usually in the form of a token. The user will then forward this request to an authentication server, which will either reject or allow this authentication. From here, the token is provided to the user, and then to the requester. Such a token can then be checked at any time independently of the user by the requester for validation and can be used over time with strictly limited scope and age of validity.

This is fundamentally a much more secure and powerful system than the other approaches, mainly because it allows for the establishment of scopes which can provide access to different parts of the API service and since the token is revoked after a certain time - makes it much harder to re-use by attackers.

   Cookie bases Authentication:
Cookie authentication uses HTTP cookies to authenticate client requests and maintain session information. It works as follows:

The client sends a login request to the server.
On the successful login, the server response includes the Set-Cookie header that contains the cookie name, value, expiry time and some other info. Here is an example that sets the cookie named JSESSIONID:
Set-Cookie: JSESSIONID=abcde12345; Path=/; HttpOnly

The client needs to send this cookie in the Cookie header in all subsequent requests to the server.

Cookie: JSESSIONID=abcde12345

On the logout operation, the server sends back the Set-Cookie header that causes the cookie to expire.

 

5. What is API Gateway.

 The API Gateway encapsulates the internal system architecture and provides an API that is tailored to each client. It might have other responsibilities such as authentication, monitoring, load balancing, caching, request shaping and management, and static response handling.



The API Gateway is responsible for request routing, composition, and protocol translation. All requests from clients first go through the API Gateway. It then routes requests to the appropriate microservice. The API Gateway will often handle a request by invoking multiple microservices and aggregating the results. It can translate between web protocols such as HTTP and WebSocket and web‑unfriendly protocols that are used internally.


06. How to set up proxy in Postman?
Go to Settings--> Proxy-->Add a custom proxy configuration-->Provide Proxy Details


07. How to add certificates in Postman?
Go to Settings--> Certificates -->Import-->Add Certificate

08. What will be response code you will get after using wrong Json payload?
400- Bad request

09. What is response code you will get if server is down or not responding?
500 server error

10. When you get 201?
201 response code we will as 'created' with post call





 


12: What is web services



1. What tool to use for API testing?



3. Collections and parameters in Postman?



4. Where to check status code and headers in Postman?



5. How to set global variable in Postman?



6. How to use authentication and authorization in Postman?



7. Check response meesage in Postman?t



8. How to download the response of a request using Postman?



9 How to use collection runner?



10. Cookies and Headers also we need to validate apart from status code and response body?

11. What type of status codes you have worked ?

12. Which one has the higher priority in Postman? A global variable or a local variable?

13: Whar are the types of workspace in Postman?

14. How to run the requests in collection for multiple times?

Ans: got to Collection Runner and define the number of times require to execute the requests in "Iterations" inputbox

15. How to give delay between iteration cycle in POstman while running collection?

Ans: Use the Delay inputbox, the default time unit is in ms.

16. What are the methods in API you have used?

Ans: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS 

17. How you get request details or end points in your project and test it?

Ans: Swagger or confluence and append your server address with request in Postman.

18. How to set up proxy in Postman?

Ans: Go to Settings--> Proxy-->Add a custom proxy configuration-->Provide Proxy Details

19. How to add certificates in Postman?

Ans: Go to Settings--> Certificates -->Import-->Add Certificate

20. What variables we have in POSTMAN?

Ans: Global and Environment





2. Different HTTP Methods you are aware of in API Testing. 


GET: Fetches a resource from the server 


POST: Creates a new resource on the server. 


PUT: Updates an existing resource on the server. 


DELETE: Deletes a resource on the server 


PATCH: Updates an existing resource on the server. 


3. Commonly used Status Codes for API Testing. 


200: OK 


201: Created 


400: Bad Request 


401: Unauthorized 


403: Forbidden 


404: Not Found 


500: Internal Server Error 


503: Service Unavailable 


4. Explain your project framework? (this question is asked in all rounds) 


5. Git Commands for pushing code to the repository. 


What the interviewer meant was to tell him the process I follow from cloning the repository to push the code and creating a pull request. 


a) git clone “repo-url” 


b) git checkout -b “branch-name” //for creating a branch 


c) make changes to the code. 


d) git add . //add those changes(or staging) 


e) git commit -m”commit message” 


f) git push 


g) Creating a pull request from the Github UI to merge the branch to master. 


6). Different types of waits in Selenium. 


You can check this article: Waits in Selenium. 


7. What happens If I put both implicit and explicit code in my selenium code? 


I was like we should not use both waits together according to Selenium official documentation. 


8. Difference b/w Delete and truncate. 


DELETE: The contents of the table cannot be rolled back. It’s permanently deleted 


TRUNCATE: The tables data is temporarily deleted and can be rolled back if required. 


9. SQL query to select rows in which the date is greater than a particular date. 


SELECT * from table_name WHERE date_col > 'date' 


10. SQL query to select only rows that don’t have values in a particular column. 


SELECT * from table_name WHERE col_name IS NULL; 


11. Test cases for booking movie ticket. 


12. Test Cases for login functionality(both UI and API) 


13. Java program to count occurrences of words in a String.(Click to view program) 


Round 2 : 


1. Introduction 


2. What is Kafka? (Mentioned in my resume) 


3. What is API? With Example? 


API(Application Programming Interface) is an interface between two applications. Therefore it enables us to transfer data between these two applications. 


For Example: 


In a Client-Server architecture, the Client requests data from a server and the server responds with the requested data. 


You might be wondering where API is? 


API can be sitting on the server: 


1. Taking your request 


2. Feting data from the database. 


3. Returning you the response 


Hence acting as an interface between your request and the database. 


4. Difference between status codes 410 and 403 


401: Unauthorized Access. This means you are not able to login to the application because of a wrong username or password. 


403: Forbidden. This means you are already logged in to the application but don’t have permission to access the resource. 


5. Difference between 500 and 503 


500: Internal Server Error i.e., the server is not able to handle your request. 


503: Service Unavailable i.e., the server is available but the service is not available. 


6. Difference Between PUT and Patch 


Both are used for updating a resource on the server. 


PUT: Replaces the whole object 


PATCH: Replaces a particular field of an object 




1. what is an API? 


2. Whats the diff between Rest vs SOAP 


3. What are the different http methods 


4. What are the different status codes and when will they occur? 


5. what are the different ways you validate XML response? 


6. What are the different ways you validate rest api response 


7. How do you use POJO’s? Sample POJO code for a Json 


8. How do you pass payload to rest api call during automation? 


9. Explain your automation framework? 


10. Explain challenges that you face during automation of rest api’s 


11. What are the diff types of testing you do with an API 


12. what is the diff between regular calls vs oauth calls? 


13. How do you test security testing using API’s 


14. How do you do performance testing with API’s 


15. what is the different between Put vs Patch 

Latest top 10 API Interview Questions and Answer Set 1



Wednesday, October 14, 2020

Latest top 10 Basic API Interview Questions and Answer Set 2

1. What is JSON?
  • JSON stands for JavaScript Object Notation.
  • JSON is a lightweight format for storing and transporting data.
  • JSON is often used when data is sent from a server to a web page.
  • JSON is "self-describing" and easy to understand. 

2: What is the difference between an API and a Web service?
An API is an interface that allow applications to communicate with one another, while a web service is a network-based resource that fulfills a specific task. 
Ex. 
Webservices : ---> https://www.irctc.co.in
API: ---> https://www.irctc.co.in/API/reservation/bookreservation/

All web services are APIs, but not all APIs are web services.
Web services must require a network while APIs can be on- or offline.

3. What tool to use for API testing?
  • Postman
  • Rest Assured
  • SOAPUI
  • Katalon
  • Karate
  • Tricentis TOSCA
  • UFT
  • Jmeter

4. What all http code return on CRUD operations? 
                                    OR 
      What type of status codes you have worked ?
CREAT(POST) 
  • 200 OK - It’s the basic status code to tell the client everything went good
  • 201 Created - It defines that the resource has been created successfully
READ(GET) 
  • 200 OK - Most of the GET actions return with a 200 OK status.
  • 206 Partial Content - This response code indicates that the request has succeeded and has the body contains the requested ranges of data, as described in the Range header of the request.
  • 404 Not Found - API could not find what requested
UPDATE(PUT/PATCH)  
  • 200 OK - This is the most appropriate code for most use-cases.
  • 204 No Content - A proper code for updates that don’t return data to the client
  • 202 Accepted - It shows that the update has been succeeded. 
DELETE
  • 200 OK - Some people think a delete function of any kind should return the deleted element, so a representation of the deleted element can be included in the response body.
  • 204 No Content - It tells the client the deletion is complete and return no response body (as the resource has been deleted).
  • 202 Accepted - If the deletion is asynchronous and takes some time, which is the case in distributed systems, it can be appropriate to return this code with some information or URL to tell the client when it will be deleted.

5. What is difference between Authentication and Authorization in Postman?
Authentication is about validating your credentials such as Username/User ID and password to verify your identity.
Authorization occurs after Authentication, Which determines your rights to grant you access of perticular resources.








6. How to set up proxy in Postman?
Postman-->Go to Settings--> Proxy-->Add a custom proxy configuration-->Provide Proxy Details

7. How to add certificates in Postman?
Go to Settings--> Certificates -->Import-->Add Certificate

8. Commonly used Status Codes for API Testing. 

200: OK
201: Created
204: No Content
400: Bad Request
401: Unauthorized
403: Forbidden
404: Not Found
500: Internal Server Error
503: Service Unavailable

 

9. Difference between status codes 410 and 403 
401: Unauthorized Access. This means you are not able to login to the application because of a wrong username or password.
403: Forbidden. This means you are already logged in to the application but don’t have permission to access the resource. 

10. Difference between 500 and 503 
500: Internal Server Error i.e., the server is not able to handle your request.
503: Service Unavailable i.e., the server is available but the service is not available. 


11. Postman feature provide below feature
1. Web service Client 
2. Manual Testing 
3. Automation testing - Data driven approach 
4. API Mocking 
5. API Monitoring 
6. Schema validation 
7. Newman - Integration with Jenkins 
8. API documentation 
9. Share collections 



12.How do you start API testing in a Sprint. -
1) Story details will be available in JIRA or any other agile management tools.
2) Understand the scope of the story and check any flow diagram is present, environment details, sample requests and responses, authentication types, any third party payload is getting called internally and find the data mapping sheet.
3) Prepare test cases
4) Start to validate the service by hitting valid endpoint URL with authentication (both positive and negative scenarios)
5) Capture the responses
6) Automate the scenarios in any automation based on client requirements
7) verify the swagger details to ensure the value of request is number or String


13) Challenges we faced during API Testing
It's a huge list let me highlight few things

1. Third party webservices will be down (which we are calling internally)
2. Mapping sheet info will not be updated properly so that we might end up incorrect validations.
3. In the limited amount of time we will not be able to test all the positive and negative scenarios
4. We should not assume anything in webservices testing it will backfire us so always get the clarification for all the things.
5. If you don’t know the method allows you to send string type and you pass integer! Or sending an empty parameter. Validation of parameter is necessary

How to install Java on EC2

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

All Time Popular Post