Skip to main content

Request Specification in REST Assured

Idea of creating a framework is to remove redundancy and duplicate code. If you have several APIs you will find that most of them have common code. Request and Response specification is another step towards building a framework.

Example Code: REST Assured Request Specification

public class RequestSpecificationTest 
{
	RequestSpecBuilder reqSpeBuilder; 
	static RequestSpecification reqSpec;
	
	@BeforeClass
	public void setup()
	{
		reqSpeBuilder = new RequestSpecBuilder();
		reqSpeBuilder.setBaseUri("https://reqres.in/");
		reqSpeBuilder.setBasePath("api");
		reqSpeBuilder.addQueryParam("page", "2");
//		AuthenticationScheme authScheme = RestAssured.oauth("", "", "", "");
//		reqSpeBuilder.setAuth(authScheme);
		reqSpec = reqSpeBuilder.build();
	}
	
	@Test(enabled=true)
	public void conditionalLogic()
	{
		Response res = 
		given()
			.spec(reqSpec)
		.when()
			.get("/users/");
			
		JsonPath js = new JsonPath(res.asString());
		
		int size = js.getInt("data.size()");
		String email = "michael.lawson@reqres.in";
		String temp = "";
		
		for(int i = 0; i < size; i++)
		{
			temp = js.getString("data["+i+"].email");
			if(temp.equals(email))
			{
				System.out.println(js.getString("data["+i+"]"));
				break;
			}
		}	
	}
	
	@Test(enabled=true)
	public void ArrayIterate()
	{
		Response res = given()
			.spec(reqSpec)
		.when()
			.get("/users/");
			
		JsonPath js = new JsonPath(res.asString());
		
		int size = js.getInt("data.size()");
		
		for(int i = 0; i < size; i++)
		{
			System.out.println(js.getString("data["+i+"].email"));
		}	
	}
}

In above code, Using RequestSpecBuilder You can use the builder to construct a request specification. RequestSpecification allows you to specify how the request will look like. We are setting up Base Path base URI, base Path and Query Parameters using this. Also for oauth you can use AuthenticationScheme.

Submitted by tgoswami on September 2, 2020

Tarun has 11+ years of experience in Quality Assurance in different domains like Banking, E-commerce, Health and Education.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.