Testing APIs is crucial in verifying that an application's backend services work as expected. Rest Assured, a popular Java library, is one of the best tools for testing RESTful APIs. It simplifies testing by providing a domain-specific language (DSL) that lets you perform requests, handle responses, and validate data with ease. In this post, we’ll go through how to test a GET request using Rest Assured.
What is a GET Request?
In RESTful services, a GET request is used to retrieve data from a server based on a specific URI. This is one of the most common HTTP methods and doesn’t modify data on the server; it simply fetches information. The data returned in response to a GET request often comes in JSON or XML format.
For example, if you're testing a sample API like https://jsonplaceholder.typicode.com/posts
, a GET request to /posts
would return all posts, while a GET request to /posts/1
would return only the post with ID 1
.
Setting Up Rest Assured
Step 1: Add Rest Assured Dependency to Your Project
If you’re using Maven, add the following dependency in your pom.xml
:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.0</version>
<scope>test</scope>
</dependency>
build.gradle
file:Step 2: Import Necessary Classes
You will need the following imports in your Java class:
import io.restassured.RestAssured;
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
Writing a Basic GET Request Test
Once Rest Assured is set up, you can start writing tests for GET requests. Here’s an example of a simple test that sends a GET request and verifies the response.
Example: Testing a GET Request to Retrieve All Posts
In this test:
- given() sets up the base URI.
- when() executes the GET request on the specified endpoint.
- then() verifies the response with assertions:
- statusCode(200) checks that the HTTP status code is 200.
- body("size()", greaterThan(0)) ensures that the response body contains at least one post.
Validating the Response Data
With Rest Assured, you can easily add more validations to ensure the data you receive is correct.
Example: Testing a GET Request with Path Parameters
To fetch a specific post by ID, you can pass a path parameter. Here’s an example test that retrieves the post with ID 1
and validates its contents.
@Test
public void testGetPostById() {
given()
.baseUri("https://jsonplaceholder.typicode.com")
.pathParam("postId", 1)
.when()
.get("/posts/{postId}")
.then()
.statusCode(200)
.body("id", equalTo(1))
.body("title", notNullValue())
.body("userId", equalTo(1));
}
Explanation
- pathParam("postId", 1) sets the
postId
to1
. - get("/posts/{postId}") sends the GET request with the path parameter.
- body("id", equalTo(1)) checks that the post ID in the response matches the requested ID.
- body("title", notNullValue()) verifies that the title of the post is not null.
- body("userId", equalTo(1)) checks that the user ID is correct.
Storing and Logging the Response
Logging responses can be helpful for debugging and ensuring your test captures all relevant data. Here’s how to log the response data in Rest Assured.
@Test
public void testLogResponse() {
Response response = given()
.baseUri("https://jsonplaceholder.typicode.com")
.when()
.get("/posts/1")
.then()
.statusCode(200)
.log().all() // Logs the full response
.extract().response();
System.out.println("Title of Post: " + response.path("title"));
}
Here:
- log().all() logs the entire response, including headers, status, and body.
- extract().response() extracts the response, allowing further use or inspection.