QA AND TEST AUTOMATION · PART 4 · API TESTING · JAVA · 41 OF 112

REST Assured Tutorial: API Testing in Java

API tests in Java with REST Assured and JUnit 5: the given / when / then style, request specifications for the base URL and auth, extracting a login token, checking bodies with JSON paths and Hamcrest matchers, POJOs with Jackson for requests and responses, logging only on failure, and a ShopRung coupon test that checks the real $49.99 total.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • given / when / then
  • request spec
  • token via API
  • JSON paths and matchers
  • POJOs
  • log on failure

Notes

Setup

Add REST Assured to the Maven project you built in lab four, with test scope, next to JUnit five, and add Jackson for turning JSON into Java objects. Pin the version, here five point five point zero. In test classes, import REST Assured's static methods and Hamcrest's matchers, so you can write given, when and then without a class name in front of every call.

pom.xml (test scope)
<dependency>
  <groupId>io.rest-assured
  </groupId>
  <artifactId>rest-assured
  </artifactId>
  <version>5.5.0</version>
  <scope>test</scope>
</dependency>
+ junit-jupiter, jackson-databind
import static io.restassured
  .RestAssured.*;

given / when / then

Every REST Assured test has the same shape. Given sets up the request: the base address, headers, body. When makes the call: get product one. Then checks the response: status two hundred, sku BK one oh one, price twelve hundred and fifty cents. The body checks use JSON paths, like sku or items dot size, and Hamcrest matchers, like equal to. If a check fails, the message shows the expected and actual value and the path.

A first test
@Test void productOne() {
  given()
    .baseUri("http://localhost:8080")
  .when()
    .get("/api/products/1")
  .then()
    .statusCode(200)
    .body("sku", equalTo("BK-101"))
    .body("priceCents",
          equalTo(1250));
}

Specifications

Repeating the base address in every test is a maintenance trap. Build a request specification once: base URL read from a system property with localhost as the default, content type JSON, and some logging. Every test starts with given spec shop. Point the whole suite at staging by passing dash D base URL on the Maven command line. A response specification does the same for shared checks, like content type.

A reusable spec
static RequestSpecification shop =
  new RequestSpecBuilder()
    .setBaseUri(System.getProperty(
      "baseUrl",
      "http://localhost:8080"))
    .setContentType(ContentType.JSON)
    .log(LogDetail.URI)
    .build();

given().spec(shop)...
-DbaseUrl=https://staging...

Extract a token

Most tests need a logged in user. A helper posts the email and password to the login endpoint, checks two hundred, and extracts the token with a JSON path. A map becomes the JSON body automatically. Later requests add the token with auth dot oauth two, which sends a bearer header, or with an explicit authorization header. Logging in through the API takes milliseconds, so each test can use its own user.

Login helper
static String tokenFor(String email,
                       String pw) {
  return given().spec(shop)
    .body(Map.of("email", email,
                 "password", pw))
  .when().post("/api/auth/login")
  .then().statusCode(200)
    .extract().path("token");
}
// .auth().oauth2(token) or
// .header("Authorization", ...)

The coupon test

Now the real test for rule price three. Log in as Alice. Add four notebooks, which is exactly fifty dollars. Apply save ten in lower case, because codes are not case sensitive. Then expect two hundred, a discount of five hundred cents, and a total of forty nine ninety nine, which includes four ninety nine shipping. Reset the data before each test. Switch on the coupon boundary bug and this test fails with a clear message about the coupon.

PRICE-3, end to end
String t = tokenFor(ALICE, PW);
given().spec(shop).auth().oauth2(t)
  .body(Map.of("productId", 1,
               "quantity", 4))
  .post("/api/cart/items");
given().spec(shop).auth().oauth2(t)
  .body(Map.of("code", "save10"))
.when().post("/api/cart/coupon")
.then().statusCode(200)
  .body("discountCents", is(500))
  .body("total", is("$49.99"));

Matchers and paths

JSON paths and Hamcrest matchers cover most needs. Items dot size checks a list's length. Items, index zero, dot sku reads one element, and items dot sku with has items checks values across the whole list. Nested fields use dots, like coupon dot applied. For errors, check the error code field. Time with less than checks response time, and header checks headers. Many small precise checks beat one giant string comparison.

Useful checks
.body("items.size()", is(1))
.body("items[0].sku",
      equalTo("BK-101"))
.body("items.sku",
      hasItems("BK-101"))
.body("coupon.applied", is(true))
.body("error",
      equalTo("invalid_quantity"))
.time(lessThan(500L))
.header("Content-Type",
      containsString("json"))

POJOs

For bigger responses, map the JSON to Java objects, often called POJOs; records work nicely. A cart record holds a list of line records and a total. Extract as Cart dot class, and Jackson fills it in. Now assertions are typed: the IDE completes field names and the compiler catches typos. Configure Jackson to ignore unknown fields, so an API adding a new field does not break every test. Use the same idea for request bodies.

Records as models
record Line(long productId,
  String sku, int quantity,
  long lineCents) {}
record Cart(List<Line> items,
  long totalCents) {}

Cart cart = given().spec(shop)...
  .get("/api/cart")
  .then().statusCode(200)
  .extract().as(Cart.class);
assertEquals(4999, cart.totalCents());

Logging

When an API test fails in CI, you need the request and the response. Logging everything for every test drowns the output. Turn on REST Assured's logging only if validation fails: a failing test then prints the method, address, headers and both bodies, and passing tests stay quiet. Mask tokens before reports are shared. In Part seven, Allure attaches these to a readable report.

Logs that help
RestAssured
  .enableLoggingOfRequestAnd
   ResponseIfValidationFails();

failure output then shows:
  method, URI, headers, body
  status, response body

mask tokens in shared reports
Allure can attach them (Part 7)

Common mistakes

REST Assured habits to avoid. Hard coded base URLs in every test. Getting tokens through the UI. One long test that makes ten calls and checks only the last. Checking only the status code. Comparing the whole JSON response as one string, which breaks on any harmless change like a new field. One shared user for every test. And logging everything always, which hides the one failure you are looking for.

Avoid these
  • hard-coded base URLs
  • logging in through the UI
  • one test doing 10 calls and checking only the last
  • checking only statusCode
  • asserting the whole JSON string (breaks on any change)
  • shared user across tests
  • log().all() everywhere

Say it like this

In the interview: JUnit five tests with a shared request specification, base URL from configuration, JSON content type, and logging only on failure. A helper gets tokens through the login API. Tests follow given, when, then, and check the status plus specific JSON paths or typed POJOs, never just the status. Each test resets or creates its own data, and the suite runs in CI against any environment by changing one property.

In the interview
  • "JUnit 5 tests with a shared
  • request spec: base URL from config, JSON, and logging on failure. A helper gets tokens
  • via the login API. Tests use
  • given/when/then, check status
  • and specific JSON paths or POJOs, reset or create their own data, and run in CI
  • against any environment."

Interview questions

Q1What is REST Assured?

A Java library for testing HTTP/REST APIs with a fluent given/when/then syntax, JSON and XML path assertions, Hamcrest matchers and object mapping.

Q2What goes in given, when and then?

given: request setup (base URI, headers, auth, body, params); when: the HTTP call (get, post...); then: assertions on status, headers, body and time, or extraction.

Q3How do you reuse common settings in REST Assured?

With a RequestSpecification (RequestSpecBuilder) for base URI, content type, auth and logging, and a ResponseSpecification for shared checks.

Q4How do you extract a value from a response?

.then().extract().path("token") for one value, .extract().as(MyClass.class) to map the body to an object, or .extract().response() for everything.

Q5How do you send a bearer token?

given().auth().oauth2(token) or .header("Authorization", "Bearer " + token).

Q6Why use POJOs in API tests?

Typed, readable assertions with IDE support, compile-time safety and reuse for request bodies; configure the mapper to ignore unknown fields.

Q7How do you run the same REST Assured suite against different environments?

Read the base URL from configuration (system property or environment variable) in the request spec, e.g. mvn test -DbaseUrl=...

Q8How do you debug a failing REST Assured test in CI?

Enable logging of request and response if validation fails, and attach them to the report (for example with Allure), masking secrets.