Introduction
In our previous post, we explored Basic Request Specification in REST Assured, learning how to create reusable request configurations. Now, we’ll dive into Query Parameters, a key feature for sending dynamic data in API requests. This guide is designed for beginners and experienced developers, providing clear explanations and practical examples to help you master query parameters in REST Assured.
Key Point: Query parameters allow you to filter or customize API requests by appending key-value pairs to the URL, making your tests more flexible and dynamic.
What Are Query Parameters?
Query Parameters are key-value pairs appended to the URL of an API request, typically after a question mark (?
). They are used to filter results, sort data, or provide additional context to the server. For example, in the URL https://api.example.com/users?role=admin&limit=10
, role=admin
and limit=10
are query parameters.
In REST Assured, you can easily add query parameters to your requests using methods like queryParam()
or include them in a Request Specification for reusability.
Adding Query Parameters in REST Assured
REST Assured provides several ways to add query parameters to your requests. Let’s explore the most common approaches with examples using the public API https://jsonplaceholder.typicode.com
.
Option 1: Using queryParam()
The simplest way to add query parameters is with the queryParam()
method in the given()
block.
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class QueryParamTest {
@Test
public void testSingleQueryParam() {
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 parameteruserId=1
to the request URL, resulting in/posts?userId=1
.when().get("/posts")
: Sends a GET request to fetch posts foruserId=1
.then()
: Validates the response:statusCode(200)
: Ensures the request was successful.body("[0].userId", equalTo(1))
: Verifies the first post’suserId
is 1.body("size()", greaterThan(0))
: Confirms the response contains at least one post.
Important: Query parameters are case-sensitive and must match the API’s expected keys exactly. Check the API documentation for correct parameter names.
Option 2: Adding Multiple Query Parameters
To add multiple query parameters, use multiple queryParam()
calls or the queryParams()
method for a more concise approach.
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class MultipleQueryParamTest {
@Test
public void testMultipleQueryParams() {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
given()
.queryParams("userId", 1, "id", 1)
.when()
.get("/posts")
.then()
.statusCode(200)
.body("[0].userId", equalTo(1))
.body("[0].id", equalTo(1));
}
}
Explanation:
queryParams("userId", 1, "id", 1)
: Adds multiple parameters (userId=1&id=1
) to the URL, resulting in/posts?userId=1&id=1
.- The test fetches a specific post and validates its
userId
andid
.
Option 3: Using Request Specification
For reusability, include query parameters in a Request Specification to apply them across multiple tests.
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 QueryParamSpecTest {
private static RequestSpecification requestSpec;
@BeforeAll
public static void setup() {
requestSpec = new RequestSpecBuilder()
.setBaseUri("https://jsonplaceholder.typicode.com")
.addQueryParam("userId", 1)
.addHeader("Content-Type", "application/json")
.build();
}
@Test
public void testPostsWithSpec() {
given()
.spec(requestSpec)
.when()
.get("/posts")
.then()
.statusCode(200)
.body("[0].userId", equalTo(1));
}
@Test
public void testCommentsWithSpec() {
given()
.spec(requestSpec)
.when()
.get("/comments")
.then()
.statusCode(200)
.body("[0].postId", equalTo(1));
}
}
Explanation:
addQueryParam("userId", 1)
: Adds theuserId=1
parameter to the Request Specification.@BeforeAll
: Initializes the specification once for all tests.spec(requestSpec)
: Applies the specification to each test, ensuring consistent query parameters.
Pro Tip: Use Request Specifications for query parameters that are common across tests to reduce code duplication and improve maintainability.
Step 1: Handling Dynamic Query Parameters
Sometimes, query parameters need to be dynamic (e.g., based on test data). You can override or add parameters in individual tests while using a Request Specification.
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class DynamicQueryParamTest {
@Test
public void testDynamicQueryParam() {
RequestSpecification requestSpec = new RequestSpecBuilder()
.setBaseUri("https://jsonplaceholder.typicode.com")
.addQueryParam("userId", 1)
.build();
given()
.spec(requestSpec)
.queryParam("id", 2) // Override or add a new parameter
.when()
.get("/posts")
.then()
.statusCode(200)
.body("[0].id", equalTo(2));
}
}
Explanation:
- The specification sets
userId=1
, but the test addsid=2
dynamically. - The resulting URL is
/posts?userId=1&id=2
.
Step 2: 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
- Check API Documentation: Always verify the correct query parameter names and values in the API’s documentation.
- Use Descriptive Names: Choose clear parameter names to make tests readable.
- Test with Public APIs: Practice with
jsonplaceholder.typicode.com
to experiment safely. - Enable Logging: Use
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails()
to debug issues with query parameters.
Troubleshooting Tip: If the API doesn’t return expected results, double-check the query parameter names and values. Incorrect parameters may lead to empty or invalid responses.
What’s Next?
In the next post, we’ll cover Path Parameters, exploring how to use dynamic URL segments in REST Assured for more flexible API testing. Stay tuned for more hands-on examples!