How to send GET Request in Rest Assured

How to send GET Request in Rest Assured

What we have learned so far?

Part 1 – What is Rest Assured? How to setup Rest Assured?
https://www.onlyfullstack.com/what-is-rest-assured-how-to-setup-rest-assured/

Part 2 – Sample Rest API To Test With Rest Assured
https://www.onlyfullstack.com/sample-rest-api-to-test-with-rest-assured/
 

What is HTTP?

The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. This is the foundation for data communication for the World Wide Web (i.e. internet) since 1990. HTTP is a generic and stateless protocol which can be used for other purposes as well using extensions of its request methods, error codes, and headers.
Rest APIs are built on top of HTTP protocol to share or consume the information.
HTTP have different methods based on which we can perform different operations(read / save / update / delete etc.)

What are different types of HTTP method?

1. GET
GET is used to only retrieve the data from the api

2. POST
POST is used to only save the data from the api

3. PUT
PUT is used to only update the data from the api

4. DELETE
DELETE is used to only delete the data from the api

What is HTTP GET request? 

The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data. In our employee rest  api you can hit the Get All Employees request to get the details of all the employees and you can hit the Get Employee to get the information about the employee from employee id.

Get All Employees –
HTTP Method – GET
URL – http://localhost:8088/employees
URL Parameters – No Parameters Required
Body – no body needed
Response – Array of all the employees available in the database.

get allhttp method postman rest assured tutorial onlyfullstack

Get Employee –
HTTP Method – GET
URL – http://localhost:8088/employees/1
URL Parameters – employee id of which we need the information. we have passed this information as a Path Param after employees. In above url we have passed the employee id as 1.
Body – no body needed
Response – Employee Details of employee id = 1

get http method postman rest assured tutorial onlyfullstack

How to make get request in Rest Assured?

Lets write code to automate this get request and check the output –
Rest assured http get request api automation without BDD approach – 
RestAssured class have static methods and follows the builder pattern due to which we can call methods on top of methods.

@Test
    public void getMethodWithoutBDDApproach() {
        RequestSpecification request = RestAssured.given();
        request.baseUri("http://localhost:8088");

        Response response = request.get("/employees");

        // Let's print response body.
        String responseString = response.asString();
        System.out.println("Response Details : " + responseString);

        /*
         * To perform validation on response like status code or value, we need to get
         * ValidatableResponse type of response using then() method of Response
         * interface. ValidatableResponse is also an interface.
         */
        ValidatableResponse validatableResponse = response.then();
        // It will check if status code is 200
        validatableResponse.statusCode(200);
        // It will check if status line is as expected
        validatableResponse.header("Content-Type", "application/json;charset=UTF-8");
        validatableResponse.body("[0].id", Matchers.equalTo(1));
        validatableResponse.body("[0].firstName", Matchers.equalTo("saurabh"));
        validatableResponse.body("[0].lastName", Matchers.equalTo("oza"));
        validatableResponse.body("[0].salary", Matchers.equalTo(1000));
        validatableResponse.body("[0].email", Matchers.equalTo("saurabh@abc.com"));
    }

Let’s start with some basic points about Rest Assured:-

RestAssured is a class which consists many static fields and methods.
It supports POST, GET, PUT, DELETE, HEAD, PATCH and OPTIONS requests and to verify the response of these requests.

1. Set URI
First we need to set the base uri of our api. uri is the base url without the resource. means in our case the complete url is http://localhost:8088/employees and here the uri is http://localhost:8088/ and the resource name is employees.

RequestSpecification request = RestAssured.given();
request.baseUri("http://localhost:8088/");

2. Call get method
RestAssured has a static overloaded method named get(String resourceName) which returns a reference of Response interface. In fact return type of all http methods in RestAssured class is of type Response. This response contains every details returned by hitting request i.e. response body, response headers, status code, status lines, cookies etc. Here we have captured the response and printed on console.

Response response = request.get("/employees");

3. Validate the response
To validate response like status code or value , we need to get reference of type ValidatableResponse. ValidatableResponse is an interface. Response interface has a method named “then()” which returns ValidatableResponse. In fact there is an interface called “Validatable” which has “then()” method. Response interface extends
Once we get ValidatableResponse reference, we can do many assertions. In this post, we will verify status code and status line. It consists of many validation methods.

In below code we are first validating the status code then the value of “Content-Type” header and then we are validating the first record of the employee list and comparing all the properties with expected value. We are using the JsonPath to retrieve the value from the response json. [0] means 0th index of the array and [0].id means id of first element.
Don’t worry about the JsonPath. We will learn about them in our upcoming blog.

body method takes 2 parameters, first is the json path for which the value you have to compare nd second one is the Matcher which has lots of method to compare the value.

T body(String var1, Matcher<?> var2, Object... var3);
 

/*
         * To perform validation on response like status code or value, we need to get
         * ValidatableResponse type of response using then() method of Response
         * interface. ValidatableResponse is also an interface.
         */
        ValidatableResponse validatableResponse = response.then();
        // It will check if status code is 200
        validatableResponse.statusCode(200);
        // It will check if status line is as expected
        validatableResponse.header("Content-Type", "application/json;charset=UTF-8");
        validatableResponse.body("[0].id", Matchers.equalTo(1));
        validatableResponse.body("[0].firstName", Matchers.equalTo("saurabh"));
        validatableResponse.body("[0].lastName", Matchers.equalTo("oza"));
        validatableResponse.body("[0].salary", Matchers.equalTo(1000));
        validatableResponse.body("[0].email", Matchers.equalTo("saurabh@abc.com"));

Rest assured http get request api automation with BDD approach – 
BDD is an agile software development process (Not a Software Testing process) which defines expectation from an application to behave from intended user prospective.
Each scenario is written in form of

  • Given (Pre-conditions/ Context), 
  • When (Action/Event Performed) and 
  • Then (Result/Outcomes) format.
@Test
public void getMethodWithBDDApproach() {
    RestAssured.given() //precondition is to give the base uri
        .baseUri("http://localhost:8088/")
        .when() //actual action is to perform the get request
        .get("employees")
        .then() // will return the ValidatadleResponse from the Response object
        .statusCode(200)
        .body("[0].id", Matchers.equalTo(1))
        .body("[0].firstName", Matchers.equalTo("saurabh"))
        .body("[0].lastName", Matchers.equalTo("oza"))
        .body("[0].salary", Matchers.equalTo(1000))
        .body("[0].email", Matchers.equalTo("saurabh@abc.com"));
}

BDD http get request with specific employee –

@Test
 public void getWithIdMethodWithBDDApproach() {
     String requestEmployeeId = "2";
     RestAssured.given() //precondition is to give the base uri
             .baseUri("http://localhost:8088/")
             .pathParam("employee_id", requestEmployeeId)
             .when() //actual action is to perform the get request
             .get("employees/{employee_id}")
             .then() // will return the ValidatadleResponse from the Response object
             .statusCode(200)
             .header("Content-Type", "application/json;charset=UTF-8")
             .body("id", Matchers.equalTo(2))
             .body("firstName", Matchers.equalTo("only"))
             .body("lastName", Matchers.equalTo("fullstack"))
             .body("salary", Matchers.equalTo(2000))
             .body("email", Matchers.equalTo("onlyfullstack@abc.com"));
 }

Below is the complete program for http get request method with rest assured

package onlyfullstack.httpMethods;

import io.restassured.RestAssured;
import io.restassured.module.jsv.JsonSchemaValidator;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;

public class GetHttpMethodExample {

    @Test
    public void getMethodWithoutBDDApproach() {
        RequestSpecification request = RestAssured.given();
        request.baseUri("http://localhost:8088");

        Response response = request.get("/employees");

        // Let's print response body.
        String responseString = response.asString();
        System.out.println("Response Details : " + responseString);

        /*
         * To perform validation on response like status code or value, we need to get
         * ValidatableResponse type of response using then() method of Response
         * interface. ValidatableResponse is also an interface.
         */
        ValidatableResponse validatableResponse = response.then();
        // It will check if status code is 200
        validatableResponse.statusCode(200);
        // It will check if status line is as expected
        validatableResponse.header("Content-Type", "application/json;charset=UTF-8");
        validatableResponse.body("$", Matchers.hasSize(3));
        validatableResponse.body("[0].id", Matchers.equalTo(1));
        validatableResponse.body("[0].firstName", Matchers.equalTo("saurabh"));
        validatableResponse.body("[0].lastName", Matchers.equalTo("oza"));
        validatableResponse.body("[0].salary", Matchers.equalTo(1000));
        validatableResponse.body("[0].email", Matchers.equalTo("saurabh@abc.com"));
    }

    @Test
    public void getMethodWithBDDApproach() {
        RestAssured.given() //precondition is to give the base uri
                .baseUri("http://localhost:8088/")
                .when() //actual action is to perform the get request
                .get("employees")
                .then() // will return the ValidatadleResponse from the Response object
                .statusCode(200)
                .header("Content-Type", "application/json;charset=UTF-8")
                .body("[0].id", Matchers.equalTo(1))
                .body("[0].firstName", Matchers.equalTo("saurabh"))
                .body("[0].lastName", Matchers.equalTo("oza"))
                .body("[0].salary", Matchers.equalTo(1000))
                .body("[0].email", Matchers.equalTo("saurabh@abc.com"));
    }

    @Test
    public void getWithIdMethodWithBDDApproach() {
        String requestEmployeeId = "2";
        RestAssured.given() //precondition is to give the base uri
                .baseUri("http://localhost:8088/")
                .pathParam("employee_id", requestEmployeeId)
                .when() //actual action is to perform the get request
                .get("employees/{employee_id}")
                .then() // will return the ValidatadleResponse from the Response object
                .statusCode(200)
                .header("Content-Type", "application/json;charset=UTF-8")
                .body("id", Matchers.equalTo(2))
                .body("firstName", Matchers.equalTo("only"))
                .body("lastName", Matchers.equalTo("fullstack"))
                .body("salary", Matchers.equalTo(2000))
                .body("email", Matchers.equalTo("onlyfullstack@abc.com"));
    }
}

Lets go to our next tutorial where we will discuss below points :

Part 4 – How to make a POST Request using Rest Assured

 – What is POST?
 – How to make a POST Request using Rest Assured?
 – Rest assured http post request api automation without BDD approach
– Rest assured get api automation with BDD approach
https://www.onlyfullstack.com/how-to-send-post-request-in-rest-assured/

Source Code
You can find the complete source code on below GitHub repository – 
https://github.com/onlyfullstack/rest-assured-tutorial

Rest Assured Tutorial
https://www.onlyfullstack.com/rest-assured-tutorial-for-beginners/