Java with Rest Assured - 25 Frequently Asked Questions with Code
### Java with Rest Assured - 25 Questions with Code
1. How to set base URI?
RestAssured.baseURI = "https://api.example.com";
2. How to send a GET request?
Response response = RestAssured.get("/users");
System.out.println(response.asString());
3. How to validate status code?
RestAssured.get("/users").then().statusCode(200);
4. How to extract response body?
String body = RestAssured.get("/users").getBody().asString();
5. How to send a POST request with JSON?
given().header("Content-Type", "application/json")
.body("{"name":"John"}")
.when().post("/users")
.then().statusCode(201);
6. How to set path parameters?
given().pathParam("id", 1)
.when().get("/users/{id}")
.then().statusCode(200);
7. How to set query parameters?
given().queryParam("page", 2)
.when().get("/users")
.then().statusCode(200);
8. How to validate a JSON field?
given().get("/users/1")
.then().body("name", equalTo("John"));
9. How to send a PUT request?
given().header("Content-Type", "application/json")
.body("{"name":"Updated John"}")
.when().put("/users/1")
.then().statusCode(200);
10. How to send a DELETE request?
when().delete("/users/1").then().statusCode(204);
11. How to send headers?
given().header("Authorization", "Bearer token123")
.when().get("/profile")
.then().statusCode(200);
12. How to log request and response?
given().log().all().when().get("/users").then().log().all();
13. How to validate response time?
get("/users").then().time(lessThan(2000L));
14. How to deserialize response to Java class?
User user = get("/users/1").as(User.class);
15. How to use RequestSpecification?
RequestSpecification req = given().baseUri("https://api.example.com");
req.get("/users").then().statusCode(200);
16. How to handle authentication?
given().auth().basic("user", "pass")
.when().get("/secure")
.then().statusCode(200);
17. How to validate content type?
get("/users").then().contentType(ContentType.JSON);
18. How to parse JSON using JsonPath?
JsonPath path = get("/users/1").jsonPath();
System.out.println(path.getString("name"));
19. How to use path parameters with multiple values?
given().pathParams("category", "books", "id", 10)
.get("/{category}/{id}")
.then().statusCode(200);
20. How to chain requests?
int id = get("/users").jsonPath().getInt("id[0]");
get("/users/" + id).then().statusCode(200);
21. How to validate list size in response?
get("/users").then().body("size()", greaterThan(0));
22. How to test response headers?
get("/users").then().header("Content-Type", "application/json; charset=utf-8");
23. How to assert boolean fields?
get("/users/1").then().body("active", equalTo(true));
24. How to test nested JSON fields?
get("/users/1").then().body("address.city", equalTo("Chennai"));
25. How to read response status line?
String statusLine = get("/users").getStatusLine();
System.out.println(statusLine);