Post

Send Every HTTP Method in REST Assured

Read, replace, patch and cancel a payment, get headers with HEAD, discover methods with OPTIONS, search with the new QUERY method, send any method by name, and test a 405.

Send Every HTTP Method in REST Assured

The Payments API lets a client read, replace, change and cancel a payment, but your tests only ever send GET and POST. A release ships where a cancelled payment can be replaced again, and no test notices. In this guide, you’ll send every HTTP method the API supports, check what each one changes from the outside, and test the methods the API must refuse.

Level: Beginner · Time: 20 minutes · Part of: Module 2: Building Requests, section 5

What You’ll Build

You’ll build a test class called HttpMethodsTest with nine tests. Each one creates a fresh payment, then reads, replaces, patches, cancels or inspects it with a different HTTP method.

One of the tests cancels a payment and then proves it can’t be replaced:

1
2
3
4
5
6
7
8
9
10
11
DELETE /api/v1/payments/pay-1 HTTP/1.1

HTTP/1.1 204 No Content

PUT /api/v1/payments/pay-1 HTTP/1.1
Content-Type: application/json

HTTP/1.1 409 Conflict
Content-type: application/problem+json; charset=utf-8

{"title":"Conflict","status":409,"detail":"Payment pay-1 is cancelled and can't be changed", ...}

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

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

In this guide, you will:

  • Read and change a payment.
  • Cancel a payment and check the effect.
  • Use the safe methods.
  • Send any method by name.
  • Test a method the resource refuses.

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 HttpMethodsTest in a new section_05 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (HttpMethodsTest.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 Fill Path Parameters in REST Assured.

Out of scope: this guide doesn’t cover extract(), which reads the new payment’s id, or ETags and conditional requests; they’re taught in Module 4 and Module 9.

Understand HTTP Methods

The problem. Each HTTP method has its own rules. PUT replaces the whole resource, PATCH changes part of it, HEAD never returns a body, and some methods must be refused. A suite that only sends GET and POST leaves most of those rules untested, including the ones that protect data, such as refusing to change a cancelled payment.

The concept. After when(), REST Assured has a method for each common HTTP method, and request(..) sends any other method by name:

MethodREST AssuredBodyWhat the Payments API does
GETget(..)NoReads a payment
POSTpost(..)YesCreates a payment
PUTput(..)YesReplaces a payment
PATCHpatch(..)YesChanges part of a payment
DELETEdelete(..)NoCancels a payment
HEADhead(..)NoLike GET, without the body
OPTIONSoptions(..)NoLists the allowed methods
QUERYquery(..)YesSearches, with the criteria in the body

When to use each. Test every method a resource allows, and at least one it refuses. For methods that change data, check the effect with a second request, not only the response to the first. Give each test its own data, so a test that cancels a payment can’t break one that reads it.

Test what a method changes, not only what it returns.

Meet the API Under Test

This guide uses two resources of the Payments API, under /api/v1. Their OPTIONS responses list the methods each allows:

PathAllow header
/paymentsPOST, GET, QUERY, HEAD, OPTIONS
/payments/{id}GET, PUT, PATCH, DELETE, HEAD, OPTIONS

The API applies these rules to a single payment:

  • PUT needs a complete, valid payment, or it answers 422 with one entry per invalid field.
  • PATCH needs the content type application/merge-patch+json, or it answers 415. It can only change reference; any other field gives a 422.
  • DELETE doesn’t remove the payment. It answers 204 No Content and sets its status to CANCELLED.
  • A cancelled payment can’t be replaced: PUT answers 409 Conflict.
  • A method that isn’t allowed gets 405 Method Not Allowed, with the same Allow header as OPTIONS.

A new payment looks like this, shortened:

1
2
3
4
5
6
7
8
9
{
    "id": "pay-1",
    "status": "RECEIVED",
    "creditorName": "Jan Jansen",
    "amount": "20.00",
    "currency": "EUR",
    "reference": "Invoice 2026-001",
    ...
}

Your tests check these fields:

  • status, which changes from RECEIVED to CANCELLED.
  • amount, creditorName and reference, which show what PUT and PATCH changed and what they left alone.

Read and Change a Payment

Set Up a Fresh Payment for Every Test

Goal: create the test class, and create a new payment before every test.

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
55
package com.javanibble.module_02.section_05;

import static com.javanibble.module_02.support.SamplePayments.validPayment;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;

import com.javanibble.payments.PaymentsApi;

import io.restassured.http.ContentType;
import io.restassured.http.Method;
import io.restassured.specification.RequestSpecification;

import java.util.Map;

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

class HttpMethodsTest {

    private static PaymentsApi api;
    private String paymentId;

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

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

    private static RequestSpecification paymentsApi() {
        return given().baseUri(api.baseUri()).port(api.port()).basePath(PaymentsApi.BASE_PATH)
                .header("X-Request-ID", "methods");
    }

    @BeforeEach
    void createPayment() {
        paymentId = paymentsApi()
            .contentType(ContentType.JSON)
            .body(validPayment("20.00"))
        .when()
            .post("/payments")
        .then()
            .statusCode(201)
            .extract().path("id");
    }
}

What’s happening:

  • The server still starts once per class in @BeforeAll, as in every other test class.
  • @BeforeEach runs before every test and creates a new payment for it, so no test depends on what another one changed.
  • extract().path("id") reads the id from the response body into the paymentId field. Module 4 covers extract().

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

Read It With GET

Goal: read the new payment.

1
2
3
4
@Test
void getReadsIt() {
    paymentsApi().when().get("/payments/{id}", paymentId).then().statusCode(200).body("status", equalTo("RECEIVED"));
}

What’s happening:

  • get(..) reads the payment that @BeforeEach created.
  • A new payment’s status is RECEIVED. The cancel test later shows it changing.

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

Replace It With PUT

Goal: replace the whole payment with a new one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void putReplacesIt() {
    Map<String, Object> replacement = validPayment("99.99");
    replacement.put("creditorName", "Emily Clarke");

    paymentsApi()
        .contentType(ContentType.JSON)
        .body(replacement)
    .when()
        .put("/payments/{id}", paymentId)
    .then()
        .statusCode(200)
        .body("amount", equalTo("99.99"))
        .body("creditorName", equalTo("Emily Clarke"));
}

What’s happening:

  • put(..) sends a complete, valid payment to the payment’s own URL.
  • The response shows the new amount and creditor name.
  • PUT replaces the whole resource, so a field you leave out is gone, not kept. Without reference in the body, the replaced payment has no reference.

Checkpoint: run the class again. Two tests pass.

Don’t send a partial body with PUT. put(..) with only {"amount":"5.00"} gets a 422 listing every missing field. Use PATCH to change a few fields.

Change Part of It With PATCH

Goal: change one field and prove the others are untouched.

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void patchChangesPartOfIt() {
    paymentsApi()
        .contentType("application/merge-patch+json")
        .body(Map.of("reference", "Rent March"))
    .when()
        .patch("/payments/{id}", paymentId)
    .then()
        .statusCode(200)
        .body("reference", equalTo("Rent March"))
        .body("amount", equalTo("20.00"));
}

What’s happening:

  • The body holds only the field to change.
  • application/merge-patch+json, from RFC 7396, tells the server how to apply it. REST Assured serializes the map to JSON because the content type ends in +json.
  • The amount check proves that the fields you didn’t send are untouched.

Checkpoint: run the class again. Three tests pass.

A merge patch has its own media type. Sent as application/json, this API answers 415 with PATCH needs application/merge-patch+json (RFC 7396), and other APIs may apply the body in a different way.

Cancel a Payment and Check the Effect

Cancel It With DELETE

Goal: cancel the payment, then prove from the outside that it’s cancelled.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void deleteCancelsIt() {
    paymentsApi().when().delete("/payments/{id}", paymentId).then().statusCode(204).body(emptyString());

    paymentsApi().when().get("/payments/{id}", paymentId).then().body("status", equalTo("CANCELLED"));

    paymentsApi()
        .contentType(ContentType.JSON)
        .body(validPayment("1.00"))
    .when()
        .put("/payments/{id}", paymentId)
    .then()
        .statusCode(409);
}

What’s happening:

  • delete(..) answers 204 No Content, and body(emptyString()) checks that there’s no body.
  • The GET that follows shows the effect: the status is now CANCELLED. The payment wasn’t removed.
  • The PUT proves the rule from the opening: a cancelled payment can’t be replaced, so the API answers 409 Conflict.

Checkpoint: run the class again. Four tests pass.

Testing what a method changes, not only what it returns, is what makes this test useful. A 204 alone would pass even if DELETE did nothing.

Use the Safe Methods

Safe methods don’t change anything on the server. GET is one; these are the others.

Get the Headers With HEAD

Goal: check that a payment exists without downloading it.

1
2
3
4
5
6
7
8
9
10
@Test
void headReturnsTheHeadersOnly() {
    paymentsApi()
    .when()
        .head("/payments/{id}", paymentId)
    .then()
        .statusCode(200)
        .contentType(ContentType.JSON)
        .body(emptyString());
}

What’s happening:

  • HEAD answers with the same status and headers as GET, but never with a body.
  • The content type is still JSON, because it describes the body a GET would return.
  • An unknown payment gets 404 from HEAD too, so it’s a cheap way to check that a resource exists.

Checkpoint: run the class again. Five tests pass.

List the Allowed Methods With OPTIONS

Goal: ask the API which methods a payment supports.

1
2
3
4
5
6
7
8
9
10
@Test
void optionsListsTheAllowedMethods() {
    paymentsApi()
    .when()
        .options("/payments/{id}", paymentId)
    .then()
        .statusCode(204)
        .header("Allow", containsString("PATCH"))
        .header("Allow", containsString("DELETE"));
}

What’s happening:

  • OPTIONS answers 204 with the header Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS.
  • containsString(..) checks for the methods that matter, so the test doesn’t break when the order changes or a method is added.

Checkpoint: run the class again. Six tests pass.

Search With QUERY

Goal: search payments with criteria in the body instead of the URL.

GET has no body, so its search criteria go in the URL. Long or sensitive criteria don’t belong there: URLs have length limits and end up in access logs. QUERY, a new method specified in an IETF draft, is safe like GET but carries its criteria in the body. REST Assured supports it since version 6.1:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void queryIsASafeMethodWithABody() {
    paymentsApi()
        .contentType(ContentType.JSON)
        .body(Map.of("currency", "EUR", "minAmount", "20.00"))
    .when()
        .query("/payments")
    .then()
        .statusCode(200)
        .body("count", greaterThanOrEqualTo(1))
        .body("payments.currency", everyItem(equalTo("EUR")));
}

What’s happening:

  • query(..) sends the criteria as a JSON body to the collection.
  • The answer has the same shape as GET /payments: a count and a payments list.
  • greaterThanOrEqualTo(1) replaces an exact count, because other tests in the class create payments on the same server. everyItem(..) checks that the filter held for every result.

Checkpoint: run the class again. Seven tests pass.

Don’t assert exact counts on shared data. Other tests add payments to the same server, so use greaterThanOrEqualTo(..) or everyItem(..), or filter on data the test created itself.

Send Any Method by Name

Use request(..)

Goal: send a method from an enum, and a custom method that isn’t in the HTTP specification.

1
2
3
4
5
6
7
8
9
10
@Test
void anyMethodByName() {
    paymentsApi().when().request(Method.GET, "/payments/{id}", paymentId).then().statusCode(200);

    paymentsApi()
    .when()
        .request("PURGE", "/echo")
    .then()
        .body("method", equalTo("PURGE"));
}

What’s happening:

  • request(Method.GET, ..) takes the method as an enum. It’s useful when the method is a parameter, such as in a parameterized test.
  • request("PURGE", ..) takes any name. Caches and CDNs use PURGE to remove an entry.
  • The echo’s method field proves the custom method arrived as sent.

Checkpoint: run the class again. Eight tests pass.

Test a Method the Resource Refuses

Expect a 405

Goal: prove the API refuses a method that a payment doesn’t support.

1
2
3
4
@Test
void aMethodTheResourceDoesntSupport() {
    paymentsApi().when().post("/payments/{id}", paymentId).then().statusCode(405);
}

What’s happening:

  • You can’t POST to a single payment, so the API answers 405 Method Not Allowed.
  • The response carries the same Allow header as OPTIONS, telling the client what it can do instead.
  • Testing the methods an API must refuse is as important as testing the ones it accepts.

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

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-02 -Dtest=HttpMethodsTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_02.section_05.HttpMethodsTest
[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.468 s -- in com.javanibble.module_02.section_05.HttpMethodsTest
[INFO]
[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Each test runs against its own payment, so you can also run any of them on its own.

Make a Test Fail

In patchChangesPartOfIt, change "application/merge-patch+json" to "application/json" and run the command again. You should see a result similar to the following:

1
2
3
[ERROR] Failures:
[ERROR]   HttpMethodsTest.patchChangesPartOfIt:91 1 expectation failed.
Expected status code <200> but was <415>.

The body is the same, but the API rejects a merge patch with the wrong media type. A 415 on a request whose body looks right usually means the content type is wrong. Add log().ifValidationFails() to see the problem details, which say PATCH needs application/merge-patch+json (RFC 7396).

Change the content type back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
415 from PATCH with PATCH needs application/merge-patch+jsonThe patch was sent as application/jsonUse contentType("application/merge-patch+json")
422 from PUT listing several missing fieldsThe body holds only the fields to changeSend a complete payment, or use PATCH
422 from PATCH with can't be changed with PATCHThe patch changes a field other than referencePatch only reference, or use PUT
409 with is cancelled and can't be changedThe payment was cancelled, for example by a test sharing itCreate the payment each test needs in @BeforeEach

Try It Yourself

Exercise 1: Try to Patch the Amount

The API only lets PATCH change reference. Add a test called patchCantChangeTheAmount that sends a merge patch with {"amount":"1.00"}. Check that the API answers 422 with exactly one error, for the field amount, and that a GET afterwards still shows the amount "20.00".

Hint

Start from patchChangesPartOfIt. Use contains("amount") on errors.field to check for exactly one error, then add a GET like the one in deleteCancelsIt.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void patchCantChangeTheAmount() {
    paymentsApi()
        .contentType("application/merge-patch+json")
        .body(Map.of("amount", "1.00"))
    .when()
        .patch("/payments/{id}", paymentId)
    .then()
        .statusCode(422)
        .body("errors.field", contains("amount"));

    paymentsApi().when().get("/payments/{id}", paymentId).then().body("amount", equalTo("20.00"));
}

Add import static org.hamcrest.Matchers.contains; to the class.

Exercise 2: Replace, Read Back and Discover

Add a test called aReplacedPaymentIsStoredAndTheCollectionSupportsQuery. Replace the payment with validPayment("45.00"), then read it back with GET and check that the amount is "45.00" and the status is still "RECEIVED". Finally, check that OPTIONS /payments answers 204 and allows QUERY.

Hint

Combine putReplacesIt, getReadsIt and optionsListsTheAllowedMethods. The OPTIONS request goes to the collection, /payments, not to one payment.

Solution
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
@Test
void aReplacedPaymentIsStoredAndTheCollectionSupportsQuery() {
    paymentsApi()
        .contentType(ContentType.JSON)
        .body(validPayment("45.00"))
    .when()
        .put("/payments/{id}", paymentId)
    .then()
        .statusCode(200);

    paymentsApi()
    .when()
        .get("/payments/{id}", paymentId)
    .then()
        .statusCode(200)
        .body("amount", equalTo("45.00"))
        .body("status", equalTo("RECEIVED"));

    paymentsApi()
    .when()
        .options("/payments")
    .then()
        .statusCode(204)
        .header("Allow", containsString("QUERY"));
}

Summary

You built HttpMethodsTest, which reads, replaces, patches and cancels a payment, inspects it with HEAD and OPTIONS, searches with QUERY, sends methods by name, and checks a 405. A cancelled payment that can be replaced again now turns a test red.

  • REST Assured has a method for every common HTTP method, and request(..) sends any other method by name.
  • PUT replaces the whole resource, so send a complete body; PATCH with application/merge-patch+json changes only the fields you send.
  • DELETE here cancels a payment, so check the effect with a GET and a refused PUT.
  • HEAD returns the headers without a body, OPTIONS lists the allowed methods, and QUERY searches with the criteria in the body.
  • Give each test its own data in @BeforeEach, and test the methods the API must refuse.

Here are the commands you used in this guide:

1
mvn test -pl module-02 -Dtest=HttpMethodsTest

What’s Next

Next: continue with Upload Files With Multipart Requests in REST Assured, which uploads a file of payments with a text field, in three different ways.

The code:

Go deeper:

Related guides:

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