Post

Test Idempotency, ETags and Pagination in REST Assured

Test the HTTP rules payment APIs depend on, covering idempotent replay with an Idempotency-Key, conditional reads with If-None-Match and 304, conditional writes with If-Match, 428 and 412, and following Link headers through every page.

Test Idempotency, ETags and Pagination in REST Assured

A client sends a payment, and the connection drops before the answer arrives. If it sends the payment again, will the money move twice? Two clients edit the same payment at the same time: whose change wins, and does the other one get lost without anyone noticing? A list of payments is too long for one response: how does a client get every one, exactly once? HTTP has a standard answer to each question, and a server can get each one subtly wrong. In this guide, you’ll test idempotent retries, conditional reads and writes, and pagination.

Level: Advanced · Time: 30 minutes · Part of: Module 9: Data-Driven Tests and API Workflows, section 4

What You’ll Build

You’ll build a test class called HttpSemanticsTest with eight tests in three nested classes: IdempotencyKeys, ETags and Pagination.

The central test of ETags plays two clients editing the same payment, and proves the first change survives:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
PATCH /api/v1/payments/pay-9 HTTP/1.1
If-Match: "pay-9-v2"
Content-Type: application/merge-patch+json

{"reference": "First"}

HTTP/1.1 200 OK
ETag: "pay-9-v3"

PATCH /api/v1/payments/pay-9 HTTP/1.1
If-Match: "pay-9-v2"
Content-Type: application/merge-patch+json

{"reference": "Second"}

HTTP/1.1 412 Precondition Failed

When you’re done, Maven reports eight passing tests:

1
2
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Make retries safe with idempotency keys.
  • Read and write conditionally with ETags.
  • Follow every page of a list.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: create HttpSemanticsTest in a new section_04 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (HttpSemanticsTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: if you haven’t cloned the examples repository yet, follow the steps in Write Parameterized API Tests With REST Assured.

Out of scope: this guide doesn’t cover HTTP caching headers such as Cache-Control, or retrying requests automatically from the client.

Understand HTTP Semantics for Payment APIs

The problem. A payment API runs over a network that drops answers, with clients that retry and act at the same time. Without rules, a retried POST pays twice, a second edit silently overwrites the first, and a client paging through a changing list misses or repeats items. Each rule lives on the server, so only a test can prove it’s there.

The concept. HTTP has a standard mechanism for each problem:

ProblemMechanismStandard
A retried POST must not pay twiceAn Idempotency-Key headerIETF draft “The Idempotency-Key HTTP Header Field”
Don’t send an unchanged resource againETag and If-None-Match, answered with 304RFC 9110, section 13
Don’t overwrite someone else’s changeIf-Match, answered with 428 or 412RFC 9110, and RFC 6585 for 428
Get a long list page by pageLink: <..>; rel="next"RFC 8288

When to use each. Test every mechanism an API promises, with at least two requests: a single request can’t show idempotency, a conflict or a second page. And check the outcome that matters, such as the winner’s change surviving, not only the status code.

Prove each rule with the second request, the one that would break it.

Meet the API Under Test

The payment lifecycle API implements all four mechanisms:

RequestBehaviour
POST /payments with Idempotency-Key201. The same key and body again: the same payment, with Idempotent-Replayed: true. The same key with another body: 422. No key: 400
GET /payments/{id}200 with an ETag such as "pay-9-v2", which changes on every change. A matching If-None-Match: 304
PATCH /payments/{id}Needs If-Match: 428 Precondition Required without it, 412 Precondition Failed when it’s stale, 409 once authorised
GET /payments?limit=..&cursor=..items, oldest first, with Link: </api/v1/payments?limit=2&cursor=pay-3>; rel="next" while there are more

The API starts with five seeded payments, pay-1 to pay-5. Each refusal has a detail, such as Send If-Match with the ETag you last read for 428 and The payment changed since you read it for 412.

Your tests check these values:

  • The status codes, and the Idempotent-Replayed, ETag and Link headers.
  • The paymentId, which proves whether a request created a new payment.
  • The reference after two edits, which proves whose change survived.

Make Retries Safe With Idempotency Keys

Set Up the Test Class

Goal: create the test class with the API and a nested class per topic.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.javanibble.module_09.section_04;

import static com.javanibble.module_09.support.PaymentsClient.createPayment;
import static com.javanibble.module_09.support.PaymentsClient.spec;
import static com.javanibble.module_09.support.PaymentsClient.validPayment;
import static io.restassured.RestAssured.given;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;

import com.javanibble.lifecycle.PaymentLifecycleApi;

import io.restassured.response.Response;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

class HttpSemanticsTest {

    private static PaymentLifecycleApi api;

    @BeforeAll
    static void startApi() {
        api = PaymentLifecycleApi.start();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    @Nested
    class IdempotencyKeys {
    }

    @Nested
    class ETags {
    }

    @Nested
    class Pagination {
    }
}

What’s happening:

  • The tests start from spec(api), not newPayment(api), because the idempotency tests choose their own key.
  • One API serves all three nested classes, so the pagination tests see the payments the others create.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

Send the Same Request Twice

Goal: prove a retry with the same key creates no second payment.

Add this test to IdempotencyKeys:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void theSameRequestTwiceCreatesOnePayment() {
    String key = UUID.randomUUID().toString();
    Map<String, Object> body = validPayment("75.00");

    String first = given(spec(api)).header("Idempotency-Key", key).body(body)
        .when().post("/payments")
        .then().statusCode(201).header("Idempotent-Replayed", nullValue())
        .extract().path("paymentId");

    given(spec(api)).header("Idempotency-Key", key).body(body)
        .when().post("/payments")
        .then()
        .statusCode(201)
        .header("Idempotent-Replayed", "true")
        .body("paymentId", equalTo(first));                  // the same payment, not a second one
}

What’s happening:

  • The second request plays a client retrying after a lost answer: the same key, the same body.
  • It gets 201 again, marked Idempotent-Replayed: true, with the first payment’s id, so no money moved twice.
  • The first response has no Idempotent-Replayed header, which proves the marker means something.

Checkpoint: run HttpSemanticsTest from your IDE. One test runs and passes.

A replay returns the payment as it is now, not a copy of the first answer. In a check, a payment authorised between the two requests came back from the replay as AUTHORISED. Check the paymentId, not the whole body, to prove a replay.

Refuse a Reused Key and a Missing One

Goal: prove the API refuses a key used for another body, and a payment without a key.

Add these tests to IdempotencyKeys:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void reusingAKeyForAnotherRequestIsAnError() {
    String key = UUID.randomUUID().toString();
    given(spec(api)).header("Idempotency-Key", key).body(validPayment("75.00"))
        .when().post("/payments").then().statusCode(201);

    given(spec(api)).header("Idempotency-Key", key).body(validPayment("76.00"))
        .when().post("/payments").then().statusCode(422);
}

@Test
void theKeyIsRequired() {
    given(spec(api)).body(validPayment("75.00")).when().post("/payments").then().statusCode(400);
}

What’s happening:

  • A key identifies one request. Another body with the same key is a client bug, and the API refuses it with 422: Idempotency-Key <key> was already used for a different request. Replaying the first answer would hide the bug.
  • A POST without a key can’t be retried safely, so it isn’t accepted: 400 with The header Idempotency-Key is required.

Checkpoint: run the class again. Three tests pass.

A retry must reuse the original key. A new key for a retry is a new payment. Generate the key once per logical request, and keep it until the request succeeds or is abandoned.

Read and Write Conditionally With ETags

Skip an Unchanged Resource

Goal: prove the API doesn’t send a resource the client already has.

Add this test to ETags:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void anUnchangedResourceIsNotSentAgain() {
    String id = createPayment(api, "20.00");
    String etag = given(spec(api)).when().get("/payments/{id}", id)
        .then().statusCode(200).extract().header("ETag");

    given(spec(api))
        .header("If-None-Match", etag)
    .when()
        .get("/payments/{id}", id)
    .then()
        .statusCode(304)                                      // Not Modified
        .body(emptyString());
}

What’s happening:

  • The ETag is a version of the resource, such as "pay-9-v2", quotes included.
  • A client that has that version asks with If-None-Match, and gets 304 Not Modified with an empty body.

Checkpoint: run the class again. Four tests pass.

Require If-Match for an Update

Goal: prove the API refuses an update that doesn’t say which version it changes.

Add this test to ETags:

1
2
3
4
5
6
7
8
@Test
void anUpdateNeedsIfMatch() {
    String id = createPayment(api, "20.00");

    given(spec(api)).contentType("application/merge-patch+json").body(Map.of("reference", "Rent"))
        .when().patch("/payments/{id}", id)
        .then().statusCode(428);                              // Precondition Required
}

What’s happening:

  • The PATCH is a JSON merge patch that sets reference, sent without If-Match.
  • The API answers 428 Precondition Required, with Send If-Match with the ETag you last read. Requiring If-Match forces every client to say which version it’s changing.

Checkpoint: run the class again. Five tests pass.

Stop a Lost Update

Goal: play two clients editing the same version, and prove the first change survives.

Add this test to ETags:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Test
void aStaleETagLosesTheRace() {
    String id = createPayment(api, "20.00");
    String etag = given(spec(api)).when().get("/payments/{id}", id).then().extract().header("ETag");

    String newEtag = given(spec(api))                         // the first writer wins ...
        .header("If-Match", etag)
        .contentType("application/merge-patch+json").body(Map.of("reference", "First"))
        .when().patch("/payments/{id}", id)
        .then().statusCode(200).header("ETag", not(equalTo(etag)))
        .extract().header("ETag");

    given(spec(api))                                          // ... the second, with the old ETag, gets 412
        .header("If-Match", etag)
        .contentType("application/merge-patch+json").body(Map.of("reference", "Second"))
        .when().patch("/payments/{id}", id)
        .then().statusCode(412);

    given(spec(api)).when().get("/payments/{id}", id)
        .then().header("ETag", newEtag).body("reference", equalTo("First"));
}

What’s happening:

  • Both clients read the same version. The first change succeeds and creates a new ETag.
  • The second client, still holding the old ETag, gets 412 Precondition Failed, with The payment changed since you read it.
  • The last request proves what matters: the winner’s change was kept. Without If-Match, the second write would have silently overwritten the first, the classic lost update.

Checkpoint: run the class again. Six tests pass.

Check the winner after a 412. A server could refuse the second write and still lose the first. Only reading the resource back proves the first change is there.

Follow Every Page of a List

Goal: collect every payment by following Link headers, without building page URLs yourself.

Add this pattern, test and helper to Pagination:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private static final Pattern NEXT = Pattern.compile("<([^>]+)>;\\s*rel=\"next\"");

@Test
void followNextLinksUntilTheLastPage() {
    List<String> ids = new ArrayList<>();
    String next = PaymentLifecycleApi.BASE_PATH + "/payments?limit=2";
    int pages = 0;
    while (next != null) {
        Response page = given(spec(api)).basePath("").when().get(next).then().statusCode(200).extract().response();
        ids.addAll(page.path("items.paymentId"));
        next = nextLink(page.header("Link"));
        pages++;
    }

    assertThat(ids).startsWith("pay-1", "pay-2", "pay-3", "pay-4", "pay-5").doesNotHaveDuplicates();
    assertThat(pages).isEqualTo((ids.size() + 1) / 2);
}

private static String nextLink(String linkHeader) {
    if (linkHeader == null) {
        return null;
    }
    Matcher matcher = NEXT.matcher(linkHeader);
    return matcher.find() ? matcher.group(1) : null;
}

What’s happening:

  • A page with more after it has a header such as Link: </api/v1/payments?limit=2&cursor=pay-3>; rel="next". nextLink(..) takes the URL out of it, or returns null when there’s none.
  • The loop follows the link, instead of building cursor=.. itself: the cursor format is the server’s business.
  • basePath("") clears the specification’s base path, because the link already starts with /api/v1.
  • The assertions check that the seeded payments come first, in order, that none appears twice, and that the number of pages fits. Other tests create payments too, so the test checks the start of the list, not its length.

Checkpoint: run the class again. Seven tests pass.

Stop at the Last Page

Goal: prove the last page has no next link.

Add this test to Pagination:

1
2
3
4
5
6
7
8
9
@Test
void theLastPageHasNoNextLink() {
    given(spec(api))
        .queryParam("limit", 100)
    .when()
        .get("/payments")
    .then()
        .header("Link", nullValue());
}

What’s happening:

  • With limit=100, every payment fits on one page, so there’s no next page.
  • A missing Link header is how the client knows to stop. A server that always sends one sends clients into an endless loop.

Checkpoint: run the class again. All eight tests pass.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-09 -Dtest=HttpSemanticsTest

You should see a result similar to the following, with one line per nested class:

1
2
3
4
5
6
7
8
9
10
11
[INFO] Running com.javanibble.module_09.section_04.HttpSemanticsTest
[INFO] Running com.javanibble.module_09.section_04.HttpSemanticsTest$IdempotencyKeys
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.343 s -- in com.javanibble.module_09.section_04.HttpSemanticsTest$IdempotencyKeys
[INFO] Running com.javanibble.module_09.section_04.HttpSemanticsTest$Pagination
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.050 s -- in com.javanibble.module_09.section_04.HttpSemanticsTest$Pagination
[INFO] Running com.javanibble.module_09.section_04.HttpSemanticsTest$ETags
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.030 s -- in com.javanibble.module_09.section_04.HttpSemanticsTest$ETags
[INFO]
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In followNextLinksUntilTheLastPage, delete .basePath("") and run the command again. You should see a result similar to the following:

1
2
3
[ERROR] Failures:
[ERROR]   HttpSemanticsTest.followNextLinksUntilTheLastPage 1 expectation failed.
Expected status code <200> but was <404>.

With the base path still set, REST Assured puts /api/v1 in front of a link that already has it. The API’s problem detail names the result: No resource at /api/v1/api/v1/payments. Any absolute path from a Link or Location header needs the base path cleared.

Put .basePath("") back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
404 with No resource at /api/v1/api/v1/..A link’s absolute path, with the base path still setAdd basePath("")
A retry creates a second paymentThe retry used a new Idempotency-KeyReuse the original key
422 with was already used for a different requestThe same key with a different bodyUse a new key for a new request
412 on an update you expect to passThe ETag is stale: the payment changed since you read itRead again, and send the new ETag
409 with can only be changed while INITIATEDThe payment was already authorisedUpdate it before authorisation
400 with limit must be between 1 and 100A page size out of rangeUse a limit from 1 to 100

Try It Yourself

Exercise 1: Refuse an Update After Authorisation

Add a test to ETags called anAuthorisedPaymentCantBeChanged. Authorise a payment, read its current ETag, and send a PATCH with If-Match and that ETag. Check that the API answers 409 with A payment can only be changed while INITIATED, it is AUTHORISED.

Hint

Authorise with given(spec(api)).when().post("/payments/{id}/authorisation", id). Read the ETag after authorising, because authorisation changes it: with the old one, you’d get 412 instead.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void anAuthorisedPaymentCantBeChanged() {
    String id = createPayment(api, "20.00");
    given(spec(api)).when().post("/payments/{id}/authorisation", id).then().statusCode(200);
    String etag = given(spec(api)).when().get("/payments/{id}", id).then().extract().header("ETag");

    given(spec(api))
        .header("If-Match", etag)
        .contentType("application/merge-patch+json").body(Map.of("reference", "Too late"))
    .when()
        .patch("/payments/{id}", id)
    .then()
        .statusCode(409)
        .body("detail", equalTo("A payment can only be changed while INITIATED, it is AUTHORISED"));
}

Exercise 2: Get the New Version After a Change

Add a test to ETags called aChangedResourceIsSentAgain. Read a payment’s ETag, change its reference with If-Match, then read it with If-None-Match and the old ETag. Check that the API answers 200, with a new ETag and the new reference.

Hint

If-None-Match only gives 304 when the ETag still matches. Use header("ETag", not(equalTo(etag))) for the new one.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
void aChangedResourceIsSentAgain() {
    String id = createPayment(api, "20.00");
    String etag = given(spec(api)).when().get("/payments/{id}", id).then().extract().header("ETag");
    given(spec(api))
        .header("If-Match", etag)
        .contentType("application/merge-patch+json").body(Map.of("reference", "Rent"))
        .when().patch("/payments/{id}", id).then().statusCode(200);

    given(spec(api))
        .header("If-None-Match", etag)
    .when()
        .get("/payments/{id}", id)
    .then()
        .statusCode(200)
        .header("ETag", not(equalTo(etag)))
        .body("reference", equalTo("Rent"));
}

Summary

You built HttpSemanticsTest, which proves a retried payment moves money once, a reused key and a missing one are refused, an unchanged payment isn’t sent again, an update needs the current ETag and keeps the winner’s change, and every page of the list can be followed to the end.

  • An Idempotency-Key makes a retried POST safe: the same key and body replay the same payment, another body is refused with 422.
  • If-None-Match with a current ETag gets 304 and no body.
  • If-Match stops lost updates: 428 without it, 412 when stale. Read the resource back to prove the winner’s change survived.
  • Follow Link: rel="next" until there’s none, check for duplicates, and clear the base path for absolute links.
  • Prove each rule with the second request, the one that would break it.

Here are the commands you used in this guide:

1
mvn test -pl module-09 -Dtest=HttpSemanticsTest

What’s Next

Next: continue with Test Asynchronous APIs With REST Assured, which waits for the payment’s settlement with Awaitility instead of a fixed sleep.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.