Post

Send Request Bodies in REST Assured

Send a JSON body as a String, a Map, a Java record or a List, send bytes and files as they are, and test the API's answer to an invalid body (422) and the wrong content type (415).

Send Request Bodies in REST Assured

Every payment test in your suite starts with the same ten-line JSON text block. To test a payment without a creditor name, you copy the block and delete a line; to test a new amount, you copy it again. In this guide, you’ll send request bodies as strings, maps, records, lists, bytes and files, learn which REST Assured sends as they are and which it turns into JSON, and test the API’s answers to bodies it rejects.

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

What You’ll Build

You’ll build a test class called RequestBodiesTest with eight tests. Six send bodies of different types and prove what arrived; two send bodies the API must reject, and check its answer.

Most of the tests send this request and check this response:

1
2
3
4
5
6
7
8
9
10
11
POST /api/v1/payments HTTP/1.1
Host: localhost:<port>
X-Request-ID: bodies
Content-Type: application/json

{"debtorIban":"NL91ABNA0417164300","creditorIban":"NL69INGB0123456789","creditorName":"Jan Jansen","amount":"12.50","currency":"EUR"}

HTTP/1.1 201 Created
Location: /api/v1/payments/pay-1

{"id":"pay-1","status":"RECEIVED","amount":"12.50", ...}

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:

  • Send JSON bodies.
  • Test the bodies the API rejects.
  • Send bodies as they are.

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 RequestBodiesTest 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 (RequestBodiesTest.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 mapping response bodies back into records, or uploading files with their names; they’re taught in Module 4 and section 6.

Understand Request Bodies

The problem. A JSON string in a text block is clear, but it’s hard to vary. Each test that needs a slightly different payment copies the whole block, and a change to the API’s fields means editing every copy. Building JSON by concatenating strings is worse: one quote in a value breaks it.

The concept. body(..) takes any object. What REST Assured does with it depends on its type:

  • Sent as it is: a String, a byte[], a File or an InputStream. REST Assured doesn’t look inside it.
  • Serialized: any other object, such as a Map, a List or a record. REST Assured turns it into JSON or XML with an object mapper, chosen from the content type. This module has Jackson 3 on the classpath, so JSON bodies are written by Jackson 3.

Whatever the body, set the content type yourself. It tells the server what the body is, and it tells REST Assured how to serialize it.

When to use each. Use a string when the exact JSON is what the test is about, such as a body with an unknown field. Use a map when a test starts from a valid body and breaks one field. Use a record for typed bodies: the compiler checks the field names. Use bytes or a file when the content comes from outside the test.

Start from a valid body and change one thing, so each test shows what it’s about.

Meet the API Under Test

This guide uses two endpoints of the Payments API, under /api/v1:

MethodPathPurpose
POST/paymentsCreate a payment from a JSON body
POST/echoDescribe the request, including its body as text

POST /payments needs three things, and answers with a different error for each one that’s missing:

RequirementIf it’s missing
The header X-Request-ID400 Bad Request
A JSON content type415 Unsupported Media Type
A valid JSON object422 with one entry per invalid field

A valid body looks like this:

1
2
3
4
5
6
7
{
    "debtorIban": "NL91ABNA0417164300",
    "creditorIban": "NL69INGB0123456789",
    "creditorName": "Jan Jansen",
    "amount": "12.50",
    "currency": "EUR"
}

The amount is a string with exactly two decimals, as in most open banking APIs, so no precision is lost. reference is optional.

An invalid body gets an RFC 9457 problem with an errors list:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
HTTP/1.1 422
Content-type: application/problem+json; charset=utf-8

{
    "type": "about:blank",
    "title": "Unprocessable Content",
    "status": 422,
    "detail": "The request has invalid fields",
    "instance": "/api/v1/payments",
    "errors": [
        { "detail": "must not be blank", "field": "creditorName" },
        { "detail": "must be a positive amount with two decimals, such as \"25.00\"", "field": "amount" }
    ]
}

Your tests check these fields:

  • The created payment’s amount, reference or creditorName, which prove the body arrived as intended.
  • The field of each entry in errors, which names every invalid field.
  • The echo’s body and bodyLength, which show exactly what was sent.

Send JSON Bodies

Set Up the Test Class

Goal: create the test class with a request record and a helper that sets the required header.

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

import static com.javanibble.module_02.support.SamplePayments.CREDITOR_IBAN;
import static com.javanibble.module_02.support.SamplePayments.DEBTOR_IBAN;
import static com.javanibble.module_02.support.SamplePayments.validPayment;
import static com.javanibble.module_02.support.SamplePayments.validPaymentJson;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.startsWith;

import com.javanibble.payments.PaymentsApi;

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

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

class RequestBodiesTest {

    record PaymentRequest(String debtorIban, String creditorIban, String creditorName, String amount, String currency) {
    }

    private static PaymentsApi api;

    @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", "bodies");
    }
}

What’s happening:

  • PaymentRequest is a record with the five required fields. You’ll use it as a typed body.
  • paymentsApi() now also sets X-Request-ID, so no test gets a 400 by forgetting it.
  • validPaymentJson(amount) and validPayment(amount) come from the module’s SamplePayments helper. The first returns the valid body as a JSON string; the second returns it as a mutable Map, with a reference added.

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

Send a JSON String

Goal: send a body exactly as written.

1
2
3
4
5
6
7
8
9
10
11
@Test
void aJsonString() {
    paymentsApi()
        .contentType(ContentType.JSON)
        .body(validPaymentJson("12.50"))
    .when()
        .post("/payments")
    .then()
        .statusCode(201)
        .body("amount", equalTo("12.50"));
}

What’s happening:

  • A String is sent exactly as written; REST Assured doesn’t parse it.
  • contentType(ContentType.JSON) tells the server the body is JSON.
  • The created payment’s amount proves the body arrived intact.

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

Always set the content type. Without it, REST Assured sends the body as text/plain; charset=ISO-8859-1, even a map it has written as JSON, and this API answers 415 with Expected a JSON body, got Content-Type 'text/plain; charset=ISO-8859-1'.

Send a Map

Goal: send a body that a test can change one field at a time.

1
2
3
4
5
6
7
8
9
10
11
@Test
void aMapIsSerializedToJson() {
    paymentsApi()
        .contentType(ContentType.JSON)
        .body(validPayment("13.00"))
    .when()
        .post("/payments")
    .then()
        .statusCode(201)
        .body("reference", equalTo("Invoice 2026-001"));
}

What’s happening:

  • A Map isn’t sent as it is, so Jackson writes each entry as a JSON field.
  • validPayment(..) includes a reference, and the response proves it arrived.
  • To vary a map, put(..) a different value or remove(..) a field.

Checkpoint: run the class again. Two tests pass.

Send a Record

Goal: send a typed body whose field names the compiler checks.

1
2
3
4
5
6
7
8
9
10
11
@Test
void aRecordIsSerializedToJson() {
    paymentsApi()
        .contentType(ContentType.JSON)
        .body(new PaymentRequest(DEBTOR_IBAN, CREDITOR_IBAN, "Emily Clarke", "14.00", "EUR"))
    .when()
        .post("/payments")
    .then()
        .statusCode(201)
        .body("creditorName", equalTo("Emily Clarke"));
}

What’s happening:

  • Jackson 3 writes each record component as a JSON field with the same name.
  • The constructor shows which fields a payment needs, and a misspelled field name doesn’t compile.

Checkpoint: run the class again. Three tests pass.

Keep amounts as strings in request bodies. A BigDecimal("12.50") is written as the JSON number 12.50, and this API rejects it with a 422: must be a positive amount with two decimals.

Send a List

Goal: send a JSON array and see what Jackson wrote.

1
2
3
4
5
6
7
8
9
10
11
@Test
void aListIsSerializedToAJsonArray() {
    paymentsApi()
        .contentType(ContentType.JSON)
        .body(List.of(Map.of("id", "a"), Map.of("id", "b")))
    .when()
        .post("/echo")
    .then()
        .body("body", startsWith("["))
        .body("body", containsString("\"id\":\"a\""));
}

What’s happening:

  • A List becomes a JSON array: here, [{"id":"a"},{"id":"b"}].
  • The echo returns the body as text, so the test can check the JSON itself.

Checkpoint: run the class again. Four tests pass.

Test the Bodies the API Rejects

Send an Invalid Body

Goal: break two fields of a valid payment and check that the API reports both.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void anInvalidBodyGivesFieldErrors() {
    Map<String, Object> payment = validPayment("0.5");
    payment.remove("creditorName");

    paymentsApi()
        .contentType(ContentType.JSON)
        .body(payment)
    .when()
        .post("/payments")
    .then()
        .statusCode(422)
        .body("errors.field", hasItems("amount", "creditorName"));
}

What’s happening:

  • "0.5" has one decimal, so the amount is invalid, and remove("creditorName") takes away a required field.
  • The API validates every field and reports all the errors at once.
  • "errors.field" collects the field of every error into a list, and hasItems(..) checks that both are in it, whatever the order.

Checkpoint: run the class again. Five tests pass.

The API reports creditorName before amount, but that order isn’t part of its contract. Use hasItems(..) rather than contains(..) unless an API promises an order.

Send the Wrong Content Type

Goal: send valid JSON that claims to be text, and check the rejection.

The only change from aJsonString is the content type:

1
2
3
4
5
6
7
8
9
10
@Test
void theWrongContentTypeIsRejected() {
    paymentsApi()
        .contentType(ContentType.TEXT)
        .body(validPaymentJson("15.00"))
    .when()
        .post("/payments")
    .then()
        .statusCode(415);
}

What’s happening:

  • The body is valid JSON, but ContentType.TEXT says it’s text.
  • The API trusts the header, not the content, and answers 415 Unsupported Media Type.

Checkpoint: run the class again. Six tests pass.

Send Bodies as They Are

Send Bytes

Goal: send raw bytes and prove every byte arrived.

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void bytesAreSentAsTheyAre() {
    byte[] content = "plain bytes".getBytes(StandardCharsets.UTF_8);

    paymentsApi()
        .contentType("application/octet-stream")
        .body(content)
    .when()
        .post("/echo")
    .then()
        .body("bodyLength", equalTo(content.length))
        .body("contentType", startsWith("application/octet-stream"));
}

What’s happening:

  • A byte[] is sent as it is, under the content type you set.
  • bodyLength equals the array’s length, so nothing was added or lost.

Checkpoint: run the class again. Seven tests pass.

Send a File

Goal: send the content of a file as the body.

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void aFileIsSentAsItsContent(@TempDir Path folder) throws IOException {
    Path file = Files.writeString(folder.resolve("payment.json"), validPaymentJson("16.00"));

    paymentsApi()
        .contentType(ContentType.JSON)
        .body(file.toFile())
    .when()
        .post("/payments")
    .then()
        .statusCode(201)
        .body("amount", equalTo("16.00"));
}

What’s happening:

  • JUnit’s @TempDir gives the test a folder that’s deleted afterwards, and Files.writeString(..) writes a payment into it.
  • body(file.toFile()) sends the file’s content, not its name.
  • In a real suite, a body file usually lives in src/test/resources.

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

Pass a File, not a Path. A Path isn’t one of the types sent as they are, so Jackson serializes it, and the body becomes the JSON string "file:///.../payment.json". Call toFile().

Run the Tests

Run the following command from the repository root:

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

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_02.section_04.RequestBodiesTest
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.454 s -- in com.javanibble.module_02.section_04.RequestBodiesTest
[INFO]
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In anInvalidBodyGivesFieldErrors, delete the line payment.remove("creditorName"); and run the command again. You should see a result similar to the following:

1
2
3
4
5
[ERROR] Failures:
[ERROR]   RequestBodiesTest.anInvalidBodyGivesFieldErrors:120 1 expectation failed.
JSON path errors.field doesn't match.
Expected: (a collection containing "amount" and a collection containing "creditorName")
  Actual: <[amount]>

The payment still has an invalid amount, so the API still answers 422, but now with one error. The Actual list shows exactly which fields the API rejected, so you can see the creditor name is no longer among them.

Put the remove(..) line back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
415 with Expected a JSON body, got Content-Type 'text/plain; charset=ISO-8859-1'The request has no content typeAdd contentType(ContentType.JSON)
400 with The header X-Request-ID is requiredThe request was built without the paymentsApi() helperAdd header("X-Request-ID", ..)
422 with must be a positive amount with two decimals for a valid-looking amountThe amount was sent as a number, such as a BigDecimalSend the amount as a string, such as "12.50"
The echo shows the body "file:///..."A Path was passed instead of a FileCall toFile()

Try It Yourself

Exercise 1: Change the Reference

Add a test called aChangedReferenceIsStored that starts from validPayment("20.00"), changes its reference to "Rent March", and posts it to /payments. Check the status code, the reference and that the new payment’s status is "RECEIVED".

Hint

Start from aMapIsSerializedToJson. Keep the map in a variable, and call put(..) before you send it.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void aChangedReferenceIsStored() {
    Map<String, Object> payment = validPayment("20.00");
    payment.put("reference", "Rent March");

    paymentsApi()
        .contentType(ContentType.JSON)
        .body(payment)
    .when()
        .post("/payments")
    .then()
        .statusCode(201)
        .body("reference", equalTo("Rent March"))
        .body("status", equalTo("RECEIVED"));
}

Exercise 2: Report Exactly Two Field Errors

Add a test called aMissingIbanAndALowerCaseCurrencyAreBothReported. Start from validPayment("21.00"), remove the debtorIban, and set the currency to "eur". Check that the API answers 422 with the problem details content type and the title "Unprocessable Content", that errors.field contains both debtorIban and currency, and that there are exactly two errors.

Hint

Combine anInvalidBodyGivesFieldErrors with the checks from Check Every Part of an HTTP Response. GPath can count a list with errors.size().

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
void aMissingIbanAndALowerCaseCurrencyAreBothReported() {
    Map<String, Object> payment = validPayment("21.00");
    payment.put("currency", "eur");
    payment.remove("debtorIban");

    paymentsApi()
        .contentType(ContentType.JSON)
        .body(payment)
    .when()
        .post("/payments")
    .then()
        .statusCode(422)
        .contentType("application/problem+json")
        .body("title", equalTo("Unprocessable Content"))
        .body("errors.field", hasItems("debtorIban", "currency"))
        .body("errors.size()", equalTo(2));
}

Summary

You built RequestBodiesTest, which sends strings, maps, records, lists, bytes and files as request bodies, and checks the API’s answers to an invalid body and the wrong content type. No test needs its own copy of the payment JSON any more.

  • A String, byte[], File or InputStream is sent exactly as it is.
  • Any other object, such as a Map, a List or a record, is serialized by the object mapper that matches the content type, Jackson 3 here.
  • Records are the clearest typed bodies, and maps are the easiest to break one field at a time.
  • Set the content type on every request with a body, or the server may reject it with a 415.
  • A 422 that lists every invalid field and a 415 for the wrong content type are part of an API’s contract, so test them too.

Here are the commands you used in this guide:

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

What’s Next

Next: continue with Send Every HTTP Method in REST Assured, which replaces, patches and cancels payments, and covers HEAD, OPTIONS and the new QUERY method.

The code:

Go deeper:

Related guides:

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