Insights Contact

Data, AI and Testing

API Automation with Rest-Assured, Java and Maven, Explained Simply

By SP Sankar

⏱ 3-minute read · open “Read more” for the details

Rest-Assured with Java and Maven is a popular choice for enterprise API testing. It combines Java’s strength with a test style that reads almost like plain English.

API automation means using code to test a payment system’s connections automatically, every time something changes, instead of testing by hand. This post explains a common setup with Java and Maven.

The bug our test data missed

One of the bugs I’m proudest of catching was tiny. Some account numbers start with a zero, like 0012345678. Somewhere in the flow, that zero disappeared.

  • To a computer, the number still looked valid.
  • To a bank, it could be another account, or no account at all.
  • Good API tests, with realistic data, catch bugs like this.
Read more: The bug our test data missed

One of the bugs I’m proudest of catching was also one of the smallest. Some account numbers start with a zero, like 0012345678. Somewhere in the flow, that zero was quietly dropped, so 0012345678 became 12345678.

To a computer that’s still a valid-looking number. To a bank it can be a different account, or no account at all.

Here’s the uncomfortable part: the bug wasn’t new. It had been there all along. Our test data simply had no account numbers starting with zero, so every test passed. Neat sample numbers, neat results.

It was the API testing that found it. A test payment with a real-style account number got rejected. When we looked at why, the account number that came out of the API (a way for two systems to talk to each other) was missing its leading zero. We caught it before it touched a single real payment.

What I took away: a test is only as good as its data. Build test data that looks like the real world, not a demo: leading zeros, long names, special characters, the maximum amount, and the odd cases your customers really have. And always check what an API returns, not just that it answered “200 OK”.

The framework at a glance

Here is the test framework in five layers.

  • Tests at the top send requests and check the responses.
  • Builders, models and utilities sit underneath.
  • Reports at the bottom show what passed and failed.
A Rest-Assured API test framework, layer by layerTestsGiven / When / Then scenariosRequest buildersHeaders, URLs, auth, bodiesPOJO modelsJSON mapped to Java classesUtilitiesTest data, OAuth2, logging, schema checksReportingAllure or Extent reports as audit evidenceAPI under testREST endpointsreturning JSONrequestresponseMaven builds and runs it · CI/CD (Jenkins or GitHub Actions) runs it on every change
A Rest-Assured API test framework, layer by layer
Read more: The framework at a glance

Read the five layers from top to bottom. The tests at the top send requests to the API on the right and check the responses that come back. Below them, request builders, data models and utilities do the supporting work, and reporting at the bottom produces the evidence. The gray bar shows that Maven builds it all and the CI/CD (automatic build, test and release of code) pipeline runs it on every change.

1. Rest-Assured: tests that read like sentences

Rest-Assured lets tests read like sentences.

  • Given: set up the request.
  • When: call the API.
  • Then: check the response.
Read more: 1. Rest-Assured: tests that read like sentences

Rest-Assured uses the Given–When–Then style:

  • Given: set up the request: base URL, headers, authentication and body.
  • When: call the API with GET, POST, PUT, PATCH or DELETE.
  • Then: check the response: status code, JSON values and response time.

For engineers: the technical detail below is optional; the rest of the post makes sense without it.

given()
    .baseUri("https://api.example.com")
    .header("Authorization", "Bearer " + token)
    .contentType("application/json")
    .body(new PaymentRequest("EUR", 100.00))
.when()
    .post("/payments")
.then()
    .statusCode(201)
    .body("status", equalTo("ACCEPTED"))
    .time(lessThan(2000L));

2. Maven: one place for all your libraries

Maven keeps every library in one place.

  • List the libraries once, in pom.xml.
  • Everyone uses the same versions.
Read more: 2. Maven: one place for all your libraries

Instead of downloading JAR files by hand, you list the libraries in pom.xml. Everyone on the team then uses the same versions of Rest-Assured, TestNG or JUnit, and Jackson for JSON. You can run every test with one command, mvn test, which is exactly what Jenkins or GitHub Actions need.

<dependency>
  <groupId>io.rest-assured</groupId>
  <artifactId>rest-assured</artifactId>
  <version>${rest-assured.version}</version>
  <scope>test</scope>
</dependency>

New to Maven? The official Maven in 5 Minutes guide shows how to create your first project.

3. The layers, and why they matter

Each layer has one job, so changes stay small.

  • Tests, request builders and data models.
  • Utilities for test data and tokens.
  • Reports with Allure or Extent.
Read more: 3. The layers, and why they matter
LayerWhat it doesWhy it helps
TestsThe Given–When–Then scenariosEasy for developers, QA and business to read
Request buildersBuild URLs, headers and bodiesNo copy-paste across tests
POJO modelsTurn JSON into Java classes, so you write response.getName()Enforces a strict data shape, which supports data governance
UtilitiesTest data, OAuth2 tokens (temporary digital keys that prove who is calling), logging, schema checks (checking the data has the expected shape)Reusable helpers keep tests short
ReportingAllure or Extent reportsVisual dashboards and audit evidence

4. A simple project structure

Keep each layer in its own folder.

  • New team members find anything in seconds.
  • A change in one place doesn’t ripple through every test.
Read more: 4. A simple project structure

Keep each layer in its own folder. A new team member can then find anything in seconds, and a change in one place does not ripple through every test.

payments-api-tests/
├── pom.xml                      (libraries and versions)
├── src/test/java/
│   ├── config/                  (base URL, timeouts per environment)
│   ├── auth/                    (gets and caches the OAuth2 token)
│   ├── specs/                   (shared request and response setup)
│   ├── models/                  (POJOs: PaymentRequest, PaymentResponse)
│   ├── data/                    (test data builders and edge cases)
│   └── tests/                   (smoke, regression, negative)
└── src/test/resources/
    ├── env/dev.properties, env/uat.properties
    └── schemas/payment-response.json

5. One shared setup for every test

Put the base URL, headers and logging in one shared setup.

  • Tests stay short and readable.
  • Never log tokens or full account numbers.
Read more: 5. One shared setup for every test

Every test needs the same base URL, headers and logging. Put them in one shared request specification (a reusable bundle of request settings), so the tests only hold what is different.

One payments rule matters here: never write tokens or full account numbers into the logs. Rest-Assured can hide the Authorization header for you.

public final class Specs {
  public static RequestSpecification payments() {
    return new RequestSpecBuilder()
        .setBaseUri(Config.get("base.url"))          // changes per environment
        .setContentType(ContentType.JSON)
        .addHeader("Authorization", "Bearer " + TokenCache.get())
        .setConfig(RestAssured.config().logConfig(
            LogConfig.logConfig().blacklistHeader("Authorization")))
        .addFilter(new AllureRestAssured())           // request and response go into the report
        .build();
  }
}

Pick the environment when you run the tests, for example mvn test -Denv=uat. The config class reads env/uat.properties. No URL is hard-coded in a test.

6. Get the token once, not in every test

Most payment APIs use OAuth2 tokens.

  • Get the token once and reuse it until it expires.
  • Keep the secret in the pipeline, never in the code.
Read more: 6. Get the token once, not in every test

Most payment APIs use OAuth2 client credentials (the test system proves who it is with an ID and secret, and gets a short-lived token back). Asking for a new token in every test is slow and can hit rate limits. Get it once and reuse it until it is close to expiring.

public final class TokenCache {
  private static String token;
  private static Instant expiresAt = Instant.EPOCH;

  public static synchronized String get() {
    if (Instant.now().isAfter(expiresAt.minusSeconds(60))) {
      Response r = given()
          .baseUri(Config.get("auth.url"))
          .formParam("grant_type", "client_credentials")
          .formParam("client_id", System.getenv("CLIENT_ID"))
          .formParam("client_secret", System.getenv("CLIENT_SECRET"))
          .post("/oauth2/token");
      token = r.path("access_token");
      expiresAt = Instant.now().plusSeconds(r.<Integer>path("expires_in"));
    }
    return token;
  }
}

The secret comes from an environment variable set by the CI pipeline, never from the code or the repository.

7. Models: describe the data once

Describe each request and response once, as a simple Java class.

  • Jackson turns it into JSON and back.
  • When the API changes, you update one place.
Read more: 7. Models: describe the data once

A POJO (plain old Java object, a simple class that only holds data) describes the shape of a request or response. Jackson turns it into JSON and back. If the API renames or drops a field, the test fails loudly instead of quietly passing.

public record PaymentRequest(
    String debtorAccount,     // keep as String, never as a number
    String creditorAccount,
    String creditorName,
    BigDecimal amount,        // BigDecimal, never double, for money
    String currency,
    String reference) {}

Two small choices here prevent real bugs:

  • Account numbers are text, not numbers. Storing them as a number is exactly how a leading zero disappears, the bug from the story above.
  • Money uses BigDecimal, not double. A double cannot hold 0.10 exactly, so totals can drift by a cent.

8. Test data that looks like the real world

This is the lesson from the leading-zero bug: test with awkward, real-looking data.

  • Leading zeros, long names and special characters.
  • Amount limits and tricky decimals.
  • Empty and missing fields.
Read more: 8. Test data that looks like the real world

This is the lesson from the leading-zero bug. Build a small library of awkward but realistic cases and run the same test against all of them.

CaseExampleWhat it catches
Leading zerosAccount 0012345678, routing number starting with 0Numbers converted to integers somewhere in the flow
Long namesA 140-character company nameFields cut short when mapped to a rail with a shorter limit
Special charactersO’Brien, Müller & Söhne, JoséBroken encoding, or characters a rail does not allow
Amount limits0.01, the maximum allowed, the maximum plus 0.01Off-by-one limit checks and rounding
Decimals100.10, 100.105, and JPY with no decimalsRounding, and currencies with different decimal places
Empty and missingNo reference, empty name, null amountMissing validation and unhelpful error messages

With TestNG, a DataProvider (a method that feeds many sets of data into one test) runs one test across every case:

@DataProvider(name = "realWorldAccounts")
public Object[][] accounts() {
  return new Object[][] {
    {"0012345678"}, {"000000001"}, {"123456789012345678"}
  };
}

@Test(dataProvider = "realWorldAccounts")
public void accountNumberIsNeverChanged(String account) {
  PaymentRequest req = TestData.validPayment().withCreditorAccount(account);

  given().spec(Specs.payments()).body(req)
  .when().post("/payments")
  .then().statusCode(201)
      .body("creditorAccount", equalTo(account));   // exact match, zeros included
}

9. Check the whole response, not just “200 OK”

An API can answer “200 OK” and still send back the wrong data.

  • Check the shape with a JSON schema.
  • Check the values: amount, currency and account.
  • Check that sensitive data is masked.
Read more: 9. Check the whole response, not just “200 OK”

An API can answer 200 and still send back the wrong data. Check three things on every important call:

  • The shape: a JSON schema (a file that describes which fields must be there and what type each one is) catches missing or renamed fields.
  • The values: the amount, currency and account that come back match what you sent.
  • The privacy: sensitive data is masked in the response.
given().spec(Specs.payments()).body(req)
.when().post("/payments")
.then()
    .statusCode(201)
    .body(matchesJsonSchemaInClasspath("schemas/payment-response.json"))
    .body("amount", equalTo("250.00"))
    .body("currency", equalTo("USD"))
    .body("debtorAccountMasked", matchesPattern("\\*+\\d{4}"));   // only the last 4 digits shown

Schema checks need one extra library in pom.xml: io.rest-assured:json-schema-validator.

10. Negative tests: what should be refused

In payments, what the API refuses matters as much as what it accepts.

  • No token, or an expired one: refused with a 401.
  • Over the limit: a clear error.
  • The same request sent twice: only one payment.
Read more: 10. Negative tests: what should be refused

In payments, what the API refuses matters as much as what it accepts. A good suite has at least as many “should fail” tests as “should pass” tests.

ScenarioExpected resultWhy it matters
No token, or an expired token401, and no payment createdOnly trusted callers can move money
Valid token, but no permission for this account403One client must never see or use another client’s account
Amount over the limit422 with a clear error codeLimits are a control, not a suggestion
Same request sent twiceOne payment onlyRetries must not pay twice
Bad JSON or a wrong field type400, with no stack trace in the replyErrors must not leak system details

The duplicate case uses an idempotency key, a unique ID the caller sends so the server can spot a repeated request. Send the same key twice, and the second call must return the first payment, not create a new one:

@Test
public void retryDoesNotPayTwice() {
  String key = UUID.randomUUID().toString();
  PaymentRequest req = TestData.validPayment();

  String firstId = given().spec(Specs.payments()).header("Idempotency-Key", key).body(req)
      .post("/payments").then().statusCode(201).extract().path("paymentId");

  given().spec(Specs.payments()).header("Idempotency-Key", key).body(req)
      .post("/payments")
  .then()
      .statusCode(anyOf(is(200), is(201)))
      .body("paymentId", equalTo(firstId));      // same payment, not a new one
}

Header names and status codes differ between APIs. Use the ones in your API’s contract; the idea stays the same.

11. Running it in the pipeline

Split the tests so the pipeline stays fast.

  • Smoke tests on every code change.
  • The full regression every night and before releases.
Read more: 11. Running it in the pipeline

Split the tests into groups so the pipeline stays fast:

  • Smoke: a few key checks, run on every code change, done in minutes.
  • Regression: the full suite, run every night and before each release.

Tag tests with @Test(groups = "smoke") and pick the group at run time. A GitHub Actions job looks like this:

name: api-tests
on: [push]
jobs:
  smoke:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with: { distribution: temurin, java-version: '17', cache: maven }
      - run: mvn -B test -Denv=uat -Dgroups=smoke
        env:
          CLIENT_ID: ${{ secrets.CLIENT_ID }}
          CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }}

Point the tests at a test environment only. A test suite that creates payments must never be able to reach production.

12. Reports as audit evidence

Every run leaves proof.

  • Each request and response is attached to the report.
  • Auditors can see exactly what was tested.
Read more: 12. Reports as audit evidence

The AllureRestAssured filter from section 5 attaches every request and response to the report. After a run, allure serve opens a dashboard with pass and fail counts, timings and the full message for each failure. Keep the report for each release: when an auditor asks “how do you know this change was tested?”, the answer is a link, not a meeting. Because the token header is hidden from the logs, the report is safe to share.

13. Common mistakes to avoid

Avoid these common mistakes.

  • Checking only the status code.
  • Neat demo data that hides real bugs.
  • Tests that depend on each other, fixed waits and no cleanup.
Read more: 13. Common mistakes to avoid
  • Checking only the status code. The leading-zero bug passed every “201 Created” check.
  • Neat demo data. 1234567890 and “John Smith” will never find an encoding or zero bug.
  • Tests that depend on each other. Each test should create its own data, so tests can run in any order and in parallel.
  • Hard-coded URLs and secrets. Keep them in config files and pipeline secrets.
  • Fixed waits. Thread.sleep(5000) makes tests slow and still flaky. For payments that finish later, check the status until it changes, with a time limit. The Awaitility library does this well.
  • No cleanup. Cancel or mark test payments when done, so test environments stay usable.

Why it works well in payments

Why this setup suits payments.

  • Java catches many data errors early.
  • It plugs straight into CI/CD pipelines.
  • Tests can prove personal data stays protected.
Read more: Why it works well in payments
  • Type safety: Java catches many data errors before the test even runs.
  • CI/CD ready: it plugs straight into delivery pipelines.
  • Governance checks: tests can confirm that personal data is masked in responses.
  • Room to grow: add contract testing (for example with Pact) so microservices don’t break each other.

My take

A clean, layered Rest-Assured framework turns API testing into readable, repeatable and auditable checks that run on every change.

Working on a payments project?

I help banks and fintechs deliver real-time payments, ISO 20022, and AI-driven AML and compliance change, from strategy to go-live.

Connect on LinkedInSee how I can help