REST Assured Tutorial 18 – Querying RequestSpecification in Rest Assured
As a part of End to End REST Assured Tutorial , in this post We will learn about “Querying RequestSpecification in Rest Assured”.
We know that RequestSpecification is used to create a request or how the request will look like. We set base URI, base path, headers, etc to request using RequestSpecification. There is a way available to query this RequestSpecification as well so that at any point of time we can retrieve details of RequestSpecification like what is base URI is set etc.
To query or retrieve details from RequestSpecification, Rest Assured provides a class named SpecificationQuerier. This class has a static method called query(RequestSpecification specification) which returns reference of QueryableRequestSpecification interface. This interface has methods to retrieve request details such as getBasePath(), getBody() etc.
package RestAssuredConcepts;
import io.restassured.RestAssured;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.specification.QueryableRequestSpecification;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.SpecificationQuerier;
public class QueryingRequestSpecificationExample {
public static void main(String[] args) {
// I am adding dummy request details for example
String JsonBody = "{\"firstName\":\"Amod\"}";
// Creating request specification using given()
RequestSpecification request1= RestAssured.given();
// Setting Base URI
request1.baseUri("https://restful-booker.herokuapp.com")
// Setting Base Path
.basePath("/booking")
.body(JsonBody)
.header("header1", "headerValue1")
.header("header2", "headerValue2");
// Querying RequestSpecification
// Use query() method of SpecificationQuerier class to query
QueryableRequestSpecification queryRequest = SpecificationQuerier.query(request1);
// get base URI
String retrieveURI = queryRequest.getBaseUri();
System.out.println("Base URI is : "+retrieveURI);
// get base Path
String retrievePath = queryRequest.getBasePath();
System.out.println("Base PATH is : "+retrievePath);
// get Body
String retrieveBody = queryRequest.getBody();
System.out.println("Body is : "+retrieveBody);
// Get Headers
Headers allHeaders = queryRequest.getHeaders();
System.out.println("Printing all headers: ");
for(Header h : allHeaders)
{
System.out.println("Header name : "+ h.getName()+" Header value is : "+h.getValue());
}
}
}
Output:-
Base URI is : https://restful-booker.herokuapp.com
Base PATH is : /booking
Body is : {"firstName":"Amod"}
Printing all headers:
Header name : header1 Header value is : headerValue1
Header name : header2 Header value is : headerValue2
You can clone/download example repo here.
If you have any doubt, feel free to comment below.If you like my posts, please like, comment, share and subscribe.#ThanksForReading
#HappyLearning
