API Vs Web Service

API methods - Get, Put, Post, Delete

Put Vs Post

Advantages - Language independent, early defect identification

Protocols - HTTP, SOAP, REST(architectural pattern)

Tools - Postman, REST Assured

API documentation - quick ref for accessing library (Swagger)

Challenges - parameter selection, parameter combination, call sequence

Rest Vs RestAssured


API Codes

Informational codes - 100 Continue, 101 Switching Protocol, 102 Processing(WebDAV), 103 Early Hints

Status codes(success) - 200 OK(Success), 201 Created, 202 Accepted

Status codes(redirectional) - 301 Moved permanently, 302 Found

Client Side error codes - 400 Bad request, 401 Unauthorized, 403 Forbidden, 404 Not found, 429 Too may requests, 402 Payment      required(Experimental) -> Reserved for future user

Server side error codes - 500 internal server error, 501 Not implemented, 502 Bad gateway, 503 Service Unavailable, 504 Gateway timed out

Authentication methods - API Key, Basic authentication, Oauth 


Sample API Programs


Program 1

import org.testing.Assert;

import io.restassured.RestAssured;

import io.restassured.response.Response;


public class GetData

{

@Test

public void testResponsecode()

{

Response resp=RestAssured.get("https://reqres.in/api/users?page=2");

int code=resp.getStatusCode();

System.out.printin(" Status code is "+code);

Assert.assertEquals(code, 200);

}


Program 2

Base URI = "";

RequestSpecification httprequest = RestAssured.given();

JSONObject requestparams = new JSONObject();

requestParams.put("Name", "xyx");

httpRequest.header("content-type", "application/json");

httpRequest.body(requestParams.toJSONString()); //payload

Response response = httprequest.request("Method.GET", "/hyderabad");

String responseBody = response.getBody.asString();



Dependencies - BDD

  RestAssured

  json-schema-validator

  json-path

  xml-path

  java-hamcrest

  **hamcrest-core(deprecated)

  **hamcrest-library(deprecated)


Dependencies - Java and TestNG 

  RestAssured

  Json-simple

  apche poi

  TestNG


Specify base URI

  RestAssured.baseURI = "http://restpai.demoqa.com/utilities/weather/city";


Request Object

  RequestSpecification httpRequest =  RestAssured.given();


Response Object

  Response response = httprequest.request(Method.GET, "/Hyderabad");

  String responseBody = response.getBody().asString();

  int statusCOde = response.getStatusCOde(); //200

  int responseTime = response.

  String statusLine = response.getStatusLine(); //HTTP/1.1 200 OK  


Request payload sending along with post request

  JSONObject requestParams = new JSONObject();

  requestParams.put("FirstName", "XYZ"); // payload  

  httpRequest.header("Content-Type", "application/json);  

  httpRequest.body(requestParams.toJSONString());

  Response response = httprequest.request(Method.POST, "/Hyderabad");

  String responseBody = response.getBody().asString();  

  String successCode = response.jsonPath().get("SuccessCode"); //OPERATION_SUCCESS


Capture details of headers from response  

  String respContentType = response.header("Content_Type")


Capture all the headers from response

  Headers allheaders = response.headers();

  for(Header header:allheaders)

  {

    s.o.p(header.getName()+" "+header.getValue());

  }


Verify the presence of a content in response body

  Assert.assertEquals(responseBody.contains("Delhi"), true)


Extract value of each node in JSON

  JsonPath jsonpath=response.jsonPath(); //extracts json portion of the response body  

  System.out.println(jsonpath.get("City"));


**Authentication API  

  Different types of autherization - Basic Auth, API Key, Bearer token

 

  //Basic authentication

  PreemptiveBasicAuthScheme authScheme=new PreemptiveBasicAuthScheme();

  authScheme.setUserName("ToolsQA");

  authScheme.setPassword("TestPassword");

  RestAssured.authentication=authscheme;


Summary

1. Define BaseURI

2. Request Object

3. Response

4. ResponseBody


Validations

-> status code

-> status line

-> response time

-> header (content-type, content-length, content-encoding etc..)


Data Driven Test

1.Prepare test data in excel

2.Add Apache poi dependency in pom.xml file

3.XL Utility file(java class file) which will read data from excel

4.Write TestNG test with DataProvider method


fi = new FileInputStream(path);

wb = new workbook(fi);

rowCount = wb.getSheet(1).getLastRowNum();

columCount= wb.getSheet(1).getRow(0).getLastCellNum();


@DataProvider(name="xyz")

string[][] readTestData()

{

  **string path = System.getProperty("user.dir")+"";  

  string empData[][]= new String[rowCount][columnCount]

  for(int i=0;i<=rowCount-1;i++

   {

     for(int j=1;j<colCount;j++

      {

        empData[i][j] = XLUtils.getCellData(i,j);

      }

{


@Test(dataProvider="xyz")

public insertData(String empID, String ename, String sal)

{


}