API Testing using Rest Assured

Sunday, April 11, 2021

How to automate POST request using Rest Assured | Rest API testing | API Testing

 To Automate an POST request using Rest Assured first we need to setup and Project in maven.

if  you have any difficulty in that section please refer this post to setup and maven project.

Now, first we need to Setup baseURI and than we need Request Object.


		RestAssured.baseURI="https://reqres.in/api/";
		
		//creating request object
		
		RequestSpecification request=RestAssured.given();
		

Since it is an POST request, we need to create a body parameter which we will send as a request payload along with some request header.


	JSONObject param= new JSONObject();
		
		param.put("QA","stock market");
		
		//adding header to the request
		
		request.header("Content-Type","application/json");


Here, i have only 1 body parameter  in the request so i have added only 1 parameter (QA,Stock market)

Now, we need to send this body parameter to the request in JSON format. 

//sending body param to the request
		
		request.body(param.toJSONString());


Now, to Fetch the response 

//fetching response
		
		Response response=request.request(Method.POST,"users");
		
		//printing response
		
		System.out.println("Response data is ==>>"+response.getBody().asString());
		

With this response object we can perform many validation, for example to validate any key(QA) value which need to be present in the response 


//verifying user details
		
		String job=response.jsonPath().get("QA");
		
		Assert.assertEquals(job,"stock market");
		


This is how we can validate POST request with Rest Assured.


I hope i was able to help you :) Happy learning

No comments:

Post a Comment