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: 

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.

Video Tutorial

About

Elix is a premium wordpress theme for portfolio, freelancer, design agencies and a wide range of other design institutions.