This REST Assured cookbook answers the "how do I…" questions that come up while writing API tests and in interviews: parameters, bodies and form data, auth, SSL, multiple assertions, JsonPath, extraction, logging, schemas, specifications, pagination, chaining and negative tests. Each recipe is a short, copy-ready snippet. Static imports assumed: io.restassured.RestAssured.* and org.hamcrest.Matchers.*.

1. Send query and path parameters

given().queryParam("page", 2).pathParam("id", 7)
.when().get("/users/{id}")
.then().statusCode(200);
Advertisement

2. Send a JSON body from a POJO, a Map or a file

given().contentType(ContentType.JSON).body(new User("Asha", "QA")).post("/users");
given().contentType(ContentType.JSON).body(Map.of("name", "Asha")).post("/users");
given().contentType(ContentType.JSON).body(new File("src/test/resources/payloads/user.json")).post("/users");

3. Send form data and URL-encoded data

// multipart/form-data (supports files)
given().multiPart("name", "Asha").multiPart("avatar", new File("avatar.png")).post("/profile");
// application/x-www-form-urlencoded
given().contentType(ContentType.URLENC).formParam("username", "asha").formParam("password", "secret").post("/login");

4. Add headers, cookies and a bearer token

given().header("X-Request-Id", "abc-123").cookie("session", sessionId).auth().oauth2(token).get("/orders");

5. Use Basic authentication

given().auth().preemptive().basic("admin", "secret").get("/admin/health");

preemptive() sends the credentials on the first request instead of waiting for a 401 challenge.

6. Skip SSL certificate validation in a test environment

given().relaxedHTTPSValidation().get("https://self-signed.qa.example.com/health");
// or for every request:
RestAssured.useRelaxedHTTPSValidation();

Only for test environments with self-signed certificates; never in production checks.

7. Make several assertions in one call

.then()
    .statusCode(200)
    .contentType(ContentType.JSON)
    .body("data.id", equalTo(7),
          "data.email", endsWith("@example.com"),
          "data.active", is(true));

8. Validate types and nested values with JsonPath

.body("order.items[0].price", equalTo(499.0f))
.body("order.items.size()", equalTo(3))
.body("order.items.sku", hasItems("A1", "B2"))
.body("order.items.findAll { it.qty > 1 }.size()", equalTo(1));

JSON numbers with decimals are read as Float by default; configure JsonConfig.numberReturnType(BIG_DECIMAL) for money values.

9. Assert the size of a JSON array

.body("data", hasSize(6))          // or
.body("data.size()", equalTo(6));

10. Extract values and the whole response

Response res = given().get("/users/7");
int id = res.path("data.id");
String email = res.jsonPath().getString("data.email");
List<String> names = res.jsonPath().getList("data.first_name");
User user = res.jsonPath().getObject("data", User.class);

11. Print or log the response

res.prettyPrint();                     // pretty-prints and returns the body as a string
given().log().all().get("/users").then().log().ifValidationFails();

12. Validate a JSON schema

.then().body(matchesJsonSchemaInClasspath("schemas/user.json"));

Needs the json-schema-validator dependency. See JSON schema validation.

13. Validate response time

.then().time(lessThan(2000L));

14. Validate headers and cookies

.then().header("Cache-Control", containsString("no-store")).cookie("session", notNullValue());

15. Reuse settings with request and response specifications

RequestSpecification req = new RequestSpecBuilder()
    .setBaseUri("https://api.example.com").setContentType(ContentType.JSON)
    .addHeader("Authorization", "Bearer " + token).build();
ResponseSpecification ok = new ResponseSpecBuilder()
    .expectStatusCode(200).expectContentType(ContentType.JSON).build();

given().spec(req).get("/users").then().spec(ok);

16. Handle pagination

List<String> all = new ArrayList<>();
int page = 1, totalPages;
do {
    JsonPath jp = given().queryParam("page", page).get("/users").jsonPath();
    all.addAll(jp.getList("data.email"));
    totalPages = jp.getInt("total_pages");
    page++;
} while (page <= totalPages);
assertEquals(all.size(), new HashSet<>(all).size(), "no duplicates across pages");

17. Upload and download files

Uploads use multiPart("file", file, mimeType); downloads use .asByteArray() and a checksum comparison. See API file upload and download testing.

18. Chain requests (create, then fetch)

int id = given().spec(req).body(newUser).post("/users").then().statusCode(201).extract().path("id");
given().spec(req).get("/users/" + id).then().statusCode(200).body("id", equalTo(id));

19. Test negative cases

given().spec(req).body(Map.of("email", "not-an-email")).post("/users")
.then().statusCode(400).body("errors[0].field", equalTo("email"));

given().baseUri(base).get("/orders").then().statusCode(401);   // no token

20. Add a filter for every request (for example Allure)

RestAssured.filters(new AllureRestAssured(), new RequestLoggingFilter(), new ResponseLoggingFilter());

FAQs

How do you send form-data in REST Assured?

Use multiPart(name, value) (and multiPart(name, file) for files) for multipart/form-data, or contentType(ContentType.URLENC) with formParam for URL-encoded forms.

How do you disable SSL validation in REST Assured?

Call relaxedHTTPSValidation() on the request or RestAssured.useRelaxedHTTPSValidation() globally, only for test environments with self-signed certificates.