How to test GET Request using Rest Assured

HOME

In the last tutorial, I explained the Setup of the REST Assured Maven Project In Eclipse IDE. In this tutorial, I will automate a GET Request. I will verify the status code, line of Status, and content of the Response.

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

 <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
</dependency>

<dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <version>5.5.5</version>
      <scope>test</scope>
</dependency>

Below are the steps to test a GET Request using Rest Assured:

Step 1 Specify the base URL to the RESTful web service using the RestAssured class.

RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1/employees";

Step 2 Every Request in the Rest-Assured library is represented by an interface called RequestSpecification. This interface allows modification of the request, like adding headers or adding authentication details.

requestSpecification = RestAssured.given();

RequestSpecification is imported from the package:

import io.restassured.specification.RequestSpecification;

Step 3 Send the request to the server and receive the response to the request made by REST Assured. This response contains every detail returned by hitting request i.e. response body, response headers, status code, status lines, cookies, etc.

response = requestSpecification.get();

The response is imported from package:

import io.restassured.response.Response;

Step 4 To validate a response like status code or value, we need to acquire a reference. This reference should be of type ValidatableResponse. ValidatableResponse is an interface. A validatable response to a request made by, REST Assured. ValidatableResponse is imported from the package:

import io.restassured.response.ValidatableResponse;

PrettyPrint() It prints the response body if possible and returns it as a string. Pretty printing is possible for content-types JSON, XML, and HTML.

Below is an example of creating a test in Non-BDD format. I have used ValidatableResponse for the assertion of the status. It is also used for the status line of the Response.

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.Test;

public class Get_NonBDDDemo {
    RequestSpecification requestSpecification;
    Response response;
    ValidatableResponse validatableResponse;

    @Test
    public void verifyStatusCode() {

        RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1/employees";

        // Create a request specification
        requestSpecification = RestAssured.given();

        // Calling GET method
        response = requestSpecification.get();

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

        /*
         * To perform validation on response, we need to get ValidatableResponse type of
         * response
         */
        validatableResponse = response.then();

        // Get status code
        validatableResponse.statusCode(200);

        // Check status line is as expected
        validatableResponse.statusLine("HTTP/1.1 200 OK");

    }
}

If you don’t want to use ValidatableResponse for the assertion, you can use Response from io.restassured .response to get the status code and status line, which are asserted using JUnit.Assert.

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.Assert;
import org.junit.Test;

public class Get_NonBDDResponseDemo {
    RequestSpecification requestSpecification;
    Response response;

    @Test
    public void verifyStatusCode() {

        RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1/employees";

        // Create a request specification
        requestSpecification = RestAssured.given();

        // Calling GET method
        response = requestSpecification.get();

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

        // Get status line
        String statusLine = response.getStatusLine();
        Assert.assertEquals(statusLine, "HTTP/1.1 200 OK");

        // Get status code
        int statusCode = response.getStatusCode();
        Assert.assertEquals(statusCode, 200);

    }
}

The output of the above program is

Below is the test implemented in BDD Format. In this test, I am asserting the data of Employee of Id 2. I have validated the name of the employee as well as the response message.

1. equalTo is used for assertion, and is imported from a static hamcrest package:

import static org.hamcrest.Matchers.equalTo;

2. given is a static import from package:

import static io.restassured.RestAssured.given;

import org.junit.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.equalTo;

public class Get_BDDDemo {

    @Test
    public void verifyUser() {

        // Given
        given()

                // When
                .when()
                .get("http://dummy.restapiexample.com/api/v1/employee/2")

                // Then
                .then()
                .statusCode(200).statusLine("HTTP/1.1 200 OK")

                // To verify booking id at index 3
                .body("data.employee_name", equalTo("Garrett Winters"))
                .body("message", equalTo("Successfully! Record has been fetched."));
    }

}

    given
    
    .when()
    .get("http://dummy.restapiexample.com/api/v1/employee/2")
    
    .then()
    .statusCode(200)
    .statusLine("HTTP/1.1 200 OK")
    
    .body("data.employee_name", equalTo("Garrett Winters"))
    .body("message", equalTo("Successfully! Record has been fetched."));
    

    That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

    Testing of SpringBoot REST Application using Serenity BDD and Rest Assured for GET Method

     HOME

    In the previous tutorial, I have explain about SpringBoot and how to perform Integration testing of SpringBoot Application in BDD format using Serenity BDD and Cucumber. In this tutorial, I will explain about the Integration testing of SpringBoot Application for GET method.

    Spring Boot is an open-source micro framework which provides Java developers with a platform to get started with an auto configurable production-grade Spring application. 

    In this tutorial, lets see a SpringBoot  REST Application and how it can be tested with the help of Rest Assured and Serenity

    Below is the structure of a SpringBoot  application project

    Below are various Java classes present in a SpringBoot REST Application/API

    • SpringBootRestServiceApplication.java – The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.
    • pom.xml – Contains all the dependencies needed to build this project. 
    • Student.java – This is JPA Entity for Student class
    • StudentRepository.java – This is JPA Repository for Student. This is created using Spring Data JpaRepository.
    • StudentController.java – Spring Rest Controller exposing all services on the student resource.
    • CustomizedExceptionHandler.java – This implements global exception handling and customize the responses based on the exception type.
    • ErrorDetails.java – Response Bean to use when exceptions are thrown from API.
    • StudentNotFoundException.java – Exception thrown from resources when student is not found.
    • data.sql –  Data is loaded from data.sql into Student table. Spring Boot would execute this script after the tables are created from the entities.

    HTTP also defines standard response codes.

    • 200 – SUCESS
    • 404 – RESOURCE NOT FOUND
    • 400 – BAD REQUEST
    • 201 – CREATED
    • 401 – UNAUTHORIZED
    • 415 – UNSUPPORTED TYPE – Representation not supported for the resource
    • 500 – SERVER ERROR 

    Let’s consider a few HTTP Methods:

    • GET : Should not update anything. Should return same result in multiple calls.

    Possible Return Codes 200 (OK) + 404 (NOT FOUND) +400 (BAD REQUEST) 

    • POST : Should create a new resource. Ideally return JSON with link to newly created resource. Same return codes as get possible. In addition – Return code 201 (CREATED) can be used.
    • PUT : Update a known resource. ex: update client details. Possible Return Codes : 200(OK) + 404 (NOT FOUND) +400 (BAD REQUEST) 
    • DELETE : Used to delete a resource. Possible Return Codes : 200(OK).

    We will create a Student Resource exposing three services using proper URIs and HTTP methods:

    • Retrieve all Students – @GetMapping(“/students”)
    • Get details of specific student – @GetMapping(“/students/{id}”)
    • Delete a student – @DeleteMapping(“/students/{id}”)
    • Create a new student – @PostMapping(“/students”)
    • Update student details – @PutMapping(“/students/{id}”)

    To Test a SpringBoot Application for GET Method, we are using Rest Assured with Serenity BDD. Below mentioned dependencies are added in POM.xml

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-test</artifactId>
       <scope>test</scope>
    </dependency>
    
    <dependency>
       <groupId>org.springframework.security</groupId>
       <artifactId>spring-security-test</artifactId>
       <scope>test</scope>
    </dependency>
    
    <dependency>
       <groupId>net.serenity-bdd</groupId>
       <artifactId>serenity-core</artifactId>
       <version>2.2.0version>
       <scope>test</scope>
    </dependency>
    
    <dependency>
       <groupId>net.serenity-bdd</groupId>
       <artifactId>serenity-spring</artifactId>
       <version>2.2.0</version>
       <scope>test</scope>
    </dependency>
    
    <dependency>
       <groupId>net.serenity-bdd</groupId>
       <artifactId>serenity-cucumber5</artifactId>
       <version>2.2.0</version>
       <scope>test</scope>
    </dependency>
    
    <dependency>
       <groupId>net.serenity-bdd</groupId>
       <artifactId>serenity-rest-assured</artifactId>
       <version>2.2.0</version>
    </dependency>
         
    <dependency>
       <groupId>net.serenity-bdd</groupId>
      <artifactId>serenity-screenplay-rest</artifactId>
       <version>2.2.0</version>
       <scope>test</scope>
    </dependency>
    

    First, let us see what are @RestController, @AutoWired, @GetMapping and @PathVariable annotations.

    1. @RestController

    SpringBoot RestController annotation is use to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the request defined handles method.

    2. @Autowired

    The Spring framework enables automatic dependency injection. In other words, by declaring all the bean dependencies in a Spring configuration file, Spring container can autowire relationships between collaborating beans. This is called Spring bean autowiring. To know more about Autowired, you can refer this tutorial.

    3. @GetMapping

    It is annotation for mapping HTTP GET requests onto specific handler methods.
    Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET)

    4. @PathVariable

    This annotation can be used to handle template variables in the request URI mapping, and use them as method parameters.
    In this example, we use @PathVariable annotation to extract the templated part of the URI represented by the variable {id}.

    A simple GET request to /students/{id} will invoke retrieveStudent with the extracted id value

    http://localhost:8080/students/1001
    

    Code of StudentController.java is below

    @RestController
    public class StudentController {
    
         @Autowired
         private StudentRepository studentRepository;
    
         @GetMapping("/students")
         public List retrieveAllStudents() {
               return studentRepository.findAll();
         }
    
         @GetMapping("/students/{id}")
         public EntityModel retrieveStudent(@PathVariable long id) {
               Optional student = studentRepository.findById(id);
               if (!student.isPresent())
                    throw new StudentNotFoundException("id-" + id);
               EntityModel resource = EntityModel.of(student.get());
    
               WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllStudents());
               resource.add(linkTo.withRel("all-students"));
               return resource;
         }
    

    Scenario 1- Below picture shows how we can execute a Get Request Method on a Resource using Postman

    Above scenario can be tested in the below way.

    @ReceiveUserDetails
     Scenario Outline: Send a valid Request to get user details
      Given I send a request to the URL "/students" to get user details
      Then the response will return status 200 and id and names and passport_no 
        
    Examples:
        |studentID    |studentNames  |studentPassportNo|
        |10010        |Tom           |A1234567         |
        |10020        |Shawn         |B1234568         |
        |10030        |John          |C1239875         |
    
    

    Test Code to test above scenario (StepDefinition file)

    @SpringBootTest(classes = com.springboot.rest.demo.SpringBootRestServiceApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
    
    public class GetStudentsDefinition {
     
         private final static String BASE_URI = "http://localhost";
         
         @LocalServerPort
         private int port;
         
         private ValidatableResponse validatableResponse;
     
         private void configureRestAssured() {
               RestAssured.baseURI = BASE_URI;
               RestAssured.port = port;
         }
     
         protected RequestSpecification getAnonymousRequest() throws NoSuchAlgorithmException {
               configureRestAssured();
               return given();
         }
     
         @Given("^I send a request to the URL \"([^\"]*)\" to get user details$")
         public void iSendARequest(String endpoint) throws Throwable {
               validatableResponse = getAnonymousRequest().contentType(ContentType.JSON)
        .when().get(endpoint).then();       
         }
     
         @Then("^the response will return status (\\d+) and id (.*) and names (.*) and passport_no (.*)$")
         public void extractResponse(int status, String id, String studentName, 
         String passportNo) {
         validatableResponse.assertThat().statusCode(equalTo(status)).body(containsString(id))
                         .body(containsString(studentName)).body(containsString(passportNo));
     
         }
    
    

    1. The @SpringBootTest annotation tells Spring Boot to look for a main configuration class (one with @SpringBootApplication, for instance) and use that to start a Spring application context.

    2. WebEnvironment.RANDOM_PORT is used to create run the application at some random server port.

    3. For assertion purpose, we use Hamcrest Matchers. Hamcrest is a framework for software tests. Hamcrest allows checking for conditions in your code via existing matchers classes. It also allows you to define your custom matcher implementations.

    import static org.hamcrest.Matchers.containsString;
    import static org.hamcrest.Matchers.equalTo;
    

    4. @LocalServerPort gets the reference of port where the server has started. It helps in building the actual request URIs to mimic real client interactions.

    5. ContentType.JSON is imported fromrestassured as well as ValidatableResponse

    Scenario 2- Below picture shows how we can execute a Get Request Method to get detail of a specific Student. Here, we want details of student of Id 10020

    @ReceiveAUserDetail
       Scenario: Send a valid Request to get user details
        Given I send a request to the URL "/students/10020" to get user detail of a specific user
        Then the response will return status 200 and name "Shawn"
    

    Test Code to test above scenario (StepDefinition file)

    @Given("^I send a request to the URL \"([^\"]*)\" to get user detail of a specific user$")
         public void sendRequestForSpecificUser(String endpoint) throws Throwable {
               validatableResponse = getAnonymousRequest().contentType(ContentType.JSON).when().get(endpoint).then();
               System.out.println("RESPONSE :" + validatableResponse.extract().asString());
         }
     
         @Then("^the response will return status (\\d+) and name \"([^\"]*)\"$")
         public void extractResponseOfSpecificUser(int status, String name) {
              validatableResponse.assertThat().statusCode(equalTo(status)).body("name", equalTo(name));
         }
    
    

    Scenario 3- Below picture shows how we can execute a Get Request Method for incorrect Student

    @IncorrectUserId
       Scenario: Send a valid Request to get user details
        Given I send a request to the URL "/students/7" to get user detail of a specific user
        Then the response will return status 404 and message "id-7"
    
    

    Test Code to test above scenario (StepDefinition file)

    @Given("^I send a request to the URL \"([^\"]*)\" to get user detail of a specific user$")
         public void sendRequestForSpecificUser(String endpoint) throws Throwable {
               validatableResponse = getAnonymousRequest().contentType(ContentType.JSON).when().get(endpoint).then();
               System.out.println("RESPONSE :" + validatableResponse.extract().asString()); 
         }
     
         @Then("^the response will return status (\\d+) and message \"([^\"]*)\"$")
         public void extractResponseOfInvalidUser(int status, String message) {
             validatableResponse.assertThat().statusCode(equalTo(status)).body("message", equalTo(message));
     
         }
    

    The next tutorial explains about the Testing of POST method in SpringBoot Application.

    How to send GET Request in JMeter

    HOME

    What is Apache JMeter?

    The Apache JMeter™ application is open source software, a 100% pure Java application designed to load test functional behavior and measure performance. It was design for testing Web Applications but has since expanded to other test functions.
    It can used to simulate a heavy load on a server, group of servers, network or object to test its strength or to analyze overall performance under different load types.

    How to send GET HTTP Request in JMeter?

    We can perform GET as well as POST operation in JMeter. In this tutorial, we will only explain how we can perform GET operation.

    Create a Test Plan in JMeter

    Step 1 – Add Thread Group

    • Select Test Plan on the tree
    • Add Thread Group                                                                                           
      • To add Thread Group: Right click on the “Test Plan” and add a new thread group: Add -> Threads (Users) -> Thread Group

    In the Thread Group control panel, enter Thread Properties as follows: We will take an example of row no 5.

    • Number of Threads: 5 – Number of users connects to the target website
    • Loop Count: 5  – Number of time to execute testing
    • Ramp-Up Period: 5 – It tells JMeter how long to delay before starting the next user. For example, if we have 5 users and a 5 -second Ramp-Up period, then the delay between starting users would be 1 second (5 seconds /5 users).

    Step 2 –  Adding JMeter elements

    The JMeter element used here is HTTP Request Sampler. In HTTP Request Control Panel, the Path field indicates which URL request you want to send.

    2.1 Add HTTP Request Sampler

    To add: Right-click on Thread Group and select: Add -> Sampler -> HTTP Request.

    Below mentioned are the values use in HTTP Request to perform the test

    • Name – HTTP Request 
    • Server Name or IP – localhost
    • Port – 8010
    • Method – GET
    • Path – /demo/helloworld/demo

    OR

    URL – https://reqres.in/api/users?page=2

    • Name – HTTP GET Request 
    • Protocol – https
    • Server Name or IP – reqres.in
    • Port –
    • Method – GET
    • Path – /api/users?page=2

    Step 3 – Adding Listeners to Test Plan

    Listeners – They shows the results of the test execution. They can show results in a different format such as a tree, table, graph or log file

    We are adding  View Result Tree listener

    View Result Tree – View Result Tree show results of the user request in basic HTML format

    To add: Right click Test Plan, Add -> Listener -> View Result Tree

    Complete Test Plan will look like as shown below

    Step 4 – Save the Test Plan

    To Save: Click File Select -> Save Test Plan as ->Give name of the Test Plan. It will be save as .jmx format.

    Sample .jmx File

    Step 5  – Run the Test Plan

    Click on Green Triangle as shown below to run the test.

    Step 6 – View the Execution Status

    Click on View Result Tree to see the status of Run. Successful request will be of Green color in the Text Section.

    Sample of Failed Request. Failed request will be of Red color in View Result Tree under Text option. This screen sows the reason for the failure of the request like Connection refused here.

    That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!