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.
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
- About 20 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can send JSON bodies built from
validPayment(..), as taught in Send Request Bodies in REST Assured, and fill path parameters, from Fill Path Parameters in REST Assured.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
HttpMethodsTestin a newsection_05package 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:
| Method | REST Assured | Body | What the Payments API does |
|---|---|---|---|
GET | get(..) | No | Reads a payment |
POST | post(..) | Yes | Creates a payment |
PUT | put(..) | Yes | Replaces a payment |
PATCH | patch(..) | Yes | Changes part of a payment |
DELETE | delete(..) | No | Cancels a payment |
HEAD | head(..) | No | Like GET, without the body |
OPTIONS | options(..) | No | Lists the allowed methods |
QUERY | query(..) | Yes | Searches, 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:
| Path | Allow header |
|---|---|
/payments | POST, GET, QUERY, HEAD, OPTIONS |
/payments/{id} | GET, PUT, PATCH, DELETE, HEAD, OPTIONS |
The API applies these rules to a single payment:
PUTneeds a complete, valid payment, or it answers422with one entry per invalid field.PATCHneeds the content typeapplication/merge-patch+json, or it answers415. It can only changereference; any other field gives a422.DELETEdoesn’t remove the payment. It answers204 No Contentand sets itsstatustoCANCELLED.- A cancelled payment can’t be replaced:
PUTanswers409 Conflict. - A method that isn’t allowed gets
405 Method Not Allowed, with the sameAllowheader asOPTIONS.
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 fromRECEIVEDtoCANCELLED.amount,creditorNameandreference, which show whatPUTandPATCHchanged 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. @BeforeEachruns before every test and creates a new payment for it, so no test depends on what another one changed.extract().path("id")reads theidfrom the response body into thepaymentIdfield. Module 4 coversextract().
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@BeforeEachcreated.- 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.
PUTreplaces the whole resource, so a field you leave out is gone, not kept. Withoutreferencein the body, the replaced payment has noreference.
Checkpoint: run the class again. Two tests pass.
Don’t send a partial body with
PUT.put(..)with only{"amount":"5.00"}gets a422listing every missing field. UsePATCHto 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
amountcheck 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 answers415withPATCH 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(..)answers204 No Content, andbody(emptyString())checks that there’s no body.- The
GETthat follows shows the effect: the status is nowCANCELLED. The payment wasn’t removed. - The
PUTproves the rule from the opening: a cancelled payment can’t be replaced, so the API answers409 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
204alone would pass even ifDELETEdid 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:
HEADanswers with the same status and headers asGET, but never with a body.- The content type is still JSON, because it describes the body a
GETwould return. - An unknown payment gets
404fromHEADtoo, 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:
OPTIONSanswers204with the headerAllow: 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: acountand apaymentslist. 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(..)oreveryItem(..), 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 usePURGEto remove an entry.- The echo’s
methodfield 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
POSTto a single payment, so the API answers405 Method Not Allowed. - The response carries the same
Allowheader asOPTIONS, 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
| Symptom | Likely cause | Fix |
|---|---|---|
415 from PATCH with PATCH needs application/merge-patch+json | The patch was sent as application/json | Use contentType("application/merge-patch+json") |
422 from PUT listing several missing fields | The body holds only the fields to change | Send a complete payment, or use PATCH |
422 from PATCH with can't be changed with PATCH | The patch changes a field other than reference | Patch only reference, or use PUT |
409 with is cancelled and can't be changed | The payment was cancelled, for example by a test sharing it | Create 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. PUTreplaces the whole resource, so send a complete body;PATCHwithapplication/merge-patch+jsonchanges only the fields you send.DELETEhere cancels a payment, so check the effect with aGETand a refusedPUT.HEADreturns the headers without a body,OPTIONSlists the allowed methods, andQUERYsearches 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:
- The finished test class:
HttpMethodsTest.java - The code and run commands for this module: Module 2 README
Go deeper:
- RFC 9110, section 9: Methods, for the meaning of every standard HTTP method.
- RFC 7396: JSON Merge Patch, for how a merge patch is applied.
- The HTTP QUERY Method (IETF draft), for the safe method with a body.
Related guides:
- Send Request Bodies in REST Assured, for the body types
PUT,PATCHandQUERYsend. - Check Every Part of an HTTP Response, where you first met a
405and itsAllowheader.
