Introduction

In our previous post, we explored Headers and Cookies in REST Assured, learning how to customize requests with metadata. Now, we’ll dive into GET Requests, one of the most common HTTP methods used to retrieve data from APIs. This guide is designed for beginners and experienced developers, offering clear explanations and practical examples to help you master GET requests in REST Assured.

Key Point: GET requests are used to retrieve resources from an API without modifying server data, making them ideal for testing data retrieval scenarios.

What is a GET Request?

A GET Request is an HTTP method used to fetch data from a server, such as retrieving a list of users, posts, or other resources. In RESTful APIs, GET requests are typically safe and idempotent, meaning they don’t alter server state and produce the same result when repeated. For example, GET /users/1 fetches details for a specific user.

REST Assured simplifies GET requests with its Given-When-Then syntax, allowing you to specify request details, send the request, and validate the response easily.

Performing GET Requests in REST Assured

Let’s explore how to perform and validate GET requests using REST Assured, using the public API https://jsonplaceholder.typicode.com for examples.

Option 1: Basic GET Request

The simplest GET request retrieves data from an endpoint and validates basic response properties.


import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class BasicGetTest {

    @Test
    public void testBasicGet() {
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

        given()
            .when()
                .get("/users/1")
            .then()
                .statusCode(200)
                .body("id", equalTo(1))
                .body("name", notNullValue())
                .body("email", containsString("@"));
    }
}

Explanation:

  • baseURI: Sets the base URL for the API to avoid repetition.
  • when().get("/users/1"): Sends a GET request to the /users/1 endpoint.
  • then(): Validates the response:
    • statusCode(200): Ensures the request was successful.
    • body("id", equalTo(1)): Verifies the user’s id is 1.
    • body("name", notNullValue()): Checks that the name field exists.
    • body("email", containsString("@")): Confirms the email contains an "@" symbol.
Important: Always validate the status code and key response fields to ensure the API returns the expected data.

Option 2: GET Request with Query Parameters

Combine GET requests with query parameters to filter or customize the response.


import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class GetWithQueryParamTest {

    @Test
    public void testGetWithQueryParam() {
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

        given()
            .queryParam("userId", 1)
            .when()
                .get("/posts")
            .then()
                .statusCode(200)
                .body("[0].userId", equalTo(1))
                .body("size()", greaterThan(0));
    }
}

Explanation:

  • queryParam("userId", 1): Adds the query parameter userId=1, resulting in /posts?userId=1.
  • body("[0].userId", equalTo(1)): Verifies the first post’s userId is 1.
  • body("size()", greaterThan(0)): Ensures the response contains at least one post.

Option 3: GET Request with Request Specification

Use a Request Specification to reuse common settings like headers or query parameters in GET requests.


import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class GetWithSpecTest {

    private static RequestSpecification requestSpec;

    @BeforeAll
    public static void setup() {
        requestSpec = new RequestSpecBuilder()
            .setBaseUri("https://jsonplaceholder.typicode.com")
            .addHeader("Accept", "application/json")
            .addQueryParam("userId", 1)
            .build();
    }

    @Test
    public void testGetPosts() {
        given()
            .spec(requestSpec)
            .when()
                .get("/posts")
            .then()
                .statusCode(200)
                .body("[0].userId", equalTo(1));
    }

    @Test
    public void testGetComments() {
        given()
            .spec(requestSpec)
            .when()
                .get("/comments")
            .then()
                .statusCode(200)
                .body("[0].postId", notNullValue());
    }
}

Explanation:

  • RequestSpecBuilder: Defines a reusable specification with the base URI, an Accept header, and a query parameter.
  • spec(requestSpec): Applies the specification to each test, ensuring consistent settings.
  • Both tests reuse the specification but target different endpoints (/posts and /comments).
Pro Tip: Use Request Specifications for GET requests to centralize common settings, reducing code duplication and improving test maintainability.

Step 1: Combining Path Parameters and Headers

GET requests often combine path parameters and headers for more complex scenarios.


import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class GetWithPathAndHeaderTest {

    @Test
    public void testGetWithPathAndHeader() {
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

        given()
            .pathParam("postId", 1)
            .header("Accept", "application/json")
            .when()
                .get("/posts/{postId}")
            .then()
                .statusCode(200)
                .body("id", equalTo(1));
    }
}

Explanation:

  • pathParam("postId", 1): Specifies the post ID in the URL (/posts/1).
  • header("Accept", "application/json"): Requests a JSON response.
  • The test validates the post’s id matches the path parameter.

Step 2: Extracting Response Data

You can extract data from a GET response for further processing or validation.


import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;

public class GetExtractResponseTest {

    @Test
    public void testExtractResponse() {
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

        Response response = given()
            .when()
                .get("/users/1")
            .then()
                .statusCode(200)
                .extract().response();

        String name = response.path("name");
        System.out.println("User Name: " + name);

        // Additional validation
        assert name != null && !name.isEmpty();
    }
}

Explanation:

  • extract().response(): Extracts the full response for further processing.
  • response.path("name"): Retrieves the name field from the JSON response.
  • This approach is useful for complex validations or logging response data.

Step 3: Verify Setup with pom.xml

Ensure your pom.xml includes the necessary dependencies for REST Assured and JUnit:



    
        io.rest-assured
        rest-assured
        5.4.0
        test
    
    
        org.junit.jupiter
        junit-jupiter
        5.10.2
        test
    
    
        org.hamcrest
        hamcrest
        2.2
        test
    

Run the tests using mvn test or your IDE’s test runner to confirm the setup.

Tips for Beginners

  • Start Simple: Begin with basic GET requests to understand the response structure.
  • Check API Documentation: Verify the endpoint and expected response format.
  • Use Public APIs: Practice with jsonplaceholder.typicode.com for safe experimentation.
  • Enable Logging: Use RestAssured.enableLoggingOfRequestAndResponseIfValidationFails() to debug issues.
Troubleshooting Tip: If a GET request returns a 404 Not Found error, check the endpoint URL, path parameters, or query parameters. Ensure they match the API’s requirements.

What’s Next?

In the next post, we’ll cover POST Requests, exploring how to create resources using REST Assured. Stay tuned for more hands-on examples!