Query Parameter in Rest Assured

Query parameters are widely used in the web service. ?’ is used immediately after the URL to append the query parameters to the URL. In the case of multiple parameters, we add an ‘&’ symbol in between each of the query parameters. It is used to filter or sort the resource. queryParam() is the syntax used for the Query parameter. 

Let us assume the URL to make a GET Call to find pet details is  “https://petstore.swagger.io/v2/pet/order?orderId=1”. Thus, in this URL, the query parameter value is 5. Now let’s see how we can use rest assured to pass this query parameter.

 

How to pass the query parameter in GET request API Test using Rest Assured?

1. Set up a request with the specified base URI

 RestAssured.baseURI = "https://petstore.swagger.io/v2/pet/order";

Base URI is the root address of the Resource. Here we are specifying to REST assured to use the above as the base URI of the service.

 

2. Specify the exact resource by passing query parameter details

RestAssured.given()

.queryParam("orderId",5)

.when()

.get();

Using queryParam() the value can be passed to the URL. In this case, the variable is defined as “orderId” assigned with the value “5” which would be finally sent to URL in the form of a get request. Thus, the complete URL is specified using the Query Parameter as mentioned above.

 

3. Response Validation

  .then().assertThat().statusCode(200);

Since it is a GET request for which we are making a call, thus the expected status code would be 200. Here, we are validating the response based on the condition where if status code from the response matches with the value 200.

Note:  Response validation of Response header and Response body can also be asserted, as discussed in previous examples. 

 

 

Complete Example Code

@Test

public void GetDetail() {


RestAssured.baseURI = "https://petstore.swagger.io/v2/pet/order";

RestAssured.given()

.queryParam("orderId",5)

.when()

.get()


.then().assertThat().statusCode(200);

}

 

Pass two query parameters in GET request API Test using Rest Assured?

Let us suppose we have a URL to fetch the student record who studies in class: 5 and section: B. The full-service URL is “http://localhost/students?class=5&section=B”. 

Here below is the sample code to pass both the query parameter:

RestAssured.given()

.queryParam("class",5).queryParam("section","B")

.when()

.get();