Post

Upload Files With Multipart Requests in REST Assured

Upload a CSV file with a text field as multipart/form-data, from a File, from bytes with a file name and with MultiPartSpecBuilder, and test a request with a missing part.

Upload Files With Multipart Requests in REST Assured

The payroll team uploads each month’s salary payments as a CSV file, through a form with a batch name and a file input. Your test sends the CSV as a JSON string, and the bulk endpoint rejects it, because a browser form with a file doesn’t send JSON. It sends multipart/form-data. In this guide, you’ll upload a file with a text field as a multipart request, in three ways, and test what happens when a part is missing.

Level: Beginner · Time: 15 minutes · Part of: Module 2: Building Requests, section 6

What You’ll Build

You’ll build a test class called MultipartUploadTest with five tests. Three upload a CSV of three salary payments, each in a different way; one shows what REST Assured sends; one proves the API rejects an upload without its file.

The upload tests send this request and check this response:

1
2
3
4
5
6
7
8
9
10
POST /api/v1/payments/bulk HTTP/1.1
Host: localhost:<port>
Content-Type: multipart/form-data; boundary=<random>

(a "batchName" text part and a "file" CSV part)

HTTP/1.1 201 Created
Content-type: application/json; charset=utf-8

{"batchName":"March salaries","fileName":"salaries.csv","fileContentType":"text/csv","count":3, ...}

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

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

In this guide, you will:

  • Upload a file.
  • Upload content from memory.
  • Check what REST Assured sends.
  • Test a request with a missing part.

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 MultipartUploadTest in a new section_06 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (MultipartUploadTest.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 multipart responses, or multipart/mixed and other multipart subtypes; see the REST Assured Usage wiki for those.

Understand Multipart Requests

The problem. A JSON body or a URL-encoded form carries one kind of data. An upload form carries several: a text field and a file, each with its own name and type. Building that body by hand means writing boundaries, headers and line breaks yourself, and one wrong byte makes the server reject it.

The concept. A multipart request has one Content-Type header, such as multipart/form-data; boundary=abc123, and a body made of parts. Each part has:

  • A control name: the name of the form field, such as batchName or file.
  • An optional file name, which tells the server the part is a file.
  • A content type, such as text/plain or text/csv.
  • The content itself.

The boundary is a random string that separates the parts. REST Assured builds all of this from multiPart(..) calls: it sets multipart/form-data, chooses the boundary and writes every part.

When to use it. Use a multipart request whenever an API expects what an HTML form with a file input sends: uploads of documents, images or batch files. For a single file with no other fields, check the API’s contract; some expect the raw file as the body instead.

Send each form field as its own part, and let REST Assured build the envelope.

Meet the API Under Test

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

MethodPathPurpose
POST/payments/bulkCreate one payment per CSV line, from a multipart upload
POST/echoDescribe the request, including its raw body

POST /payments/bulk takes two parts:

  • batchName, a text part that names the batch. Each payment created stores it as its reference.
  • file, a CSV file with a header row and one payment per line.

It answers 201 with a summary of what it received:

1
2
3
4
5
6
7
8
9
10
HTTP/1.1 201 Created
Content-type: application/json; charset=utf-8

{
    "batchName": "March salaries",
    "fileName": "salaries.csv",
    "fileContentType": "text/csv",
    "count": 3,
    "paymentIds": ["pay-1", "pay-2", "pay-3"]
}

Without the file part, it answers 400 with the detail The part 'file' is missing.

Your tests check these fields:

  • batchName, fileName and fileContentType, which show how REST Assured described each part.
  • count and paymentIds, which prove that every line of the CSV became a payment.

Upload a File

Set Up the Test Class

Goal: create the test class with the CSV every test uploads.

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

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.startsWith;

import com.javanibble.payments.PaymentsApi;

import io.restassured.builder.MultiPartSpecBuilder;
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 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 MultipartUploadTest {

    private static final String CSV = """
            debtorIban,creditorIban,creditorName,amount,currency
            NL91ABNA0417164300,NL69INGB0123456789,Jan Jansen,1200.00,EUR
            NL91ABNA0417164300,GB33BUKB20201555555555,Emily Clarke,950.00,EUR
            NL91ABNA0417164300,NL20INGB0001234567,Anna de Vries,1100.00,EUR
            """;

    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);
    }
}

What’s happening:

  • CSV holds a header row and three salary payments, so every upload creates three payments.
  • paymentsApi() doesn’t set X-Request-ID, because the bulk endpoint doesn’t require it.
  • MultiPartSpecBuilder is for the step that builds a part in full detail.

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

Upload a File From Disk

Goal: upload a CSV file and a batch name in one request.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void uploadAFile(@TempDir Path folder) throws IOException {
    Path csv = Files.writeString(folder.resolve("salaries.csv"), CSV);

    paymentsApi()
        .multiPart("batchName", "March salaries")
        .multiPart("file", csv.toFile(), "text/csv")
    .when()
        .post("/payments/bulk")
    .then()
        .statusCode(201)
        .body("batchName", equalTo("March salaries"))
        .body("fileName", equalTo("salaries.csv"))
        .body("fileContentType", startsWith("text/csv"))
        .body("count", equalTo(3))
        .body("paymentIds", hasSize(3));
}

What’s happening:

  • multiPart("batchName", "March salaries") adds a text part, with the content type text/plain.
  • multiPart("file", csv.toFile(), "text/csv") adds a file part. The file name, salaries.csv, comes from the File, and the third argument sets the part’s content type.
  • There’s no contentType(..) call: REST Assured sets multipart/form-data and the boundary itself.
  • count and paymentIds prove that each of the three lines became a payment.

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

Pass the MIME type of a file part. multiPart("file", file) without it sends the part as application/octet-stream. This API accepts that and reports it as fileContentType, but a server that checks for text/csv rejects it.

Upload Content From Memory

Upload Bytes With a File Name

Goal: upload content built in the test, without writing a file.

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void uploadBytesWithAFileName() {
    paymentsApi()
        .multiPart("batchName", "April salaries")
        .multiPart("file", "april.csv", CSV.getBytes(StandardCharsets.UTF_8), "text/csv")
    .when()
        .post("/payments/bulk")
    .then()
        .statusCode(201)
        .body("fileName", equalTo("april.csv"))
        .body("count", equalTo(3));
}

What’s happening:

  • This form of multiPart(..) takes the control name, a file name, the bytes and the MIME type.
  • The file name april.csv is passed separately, because bytes don’t have one.
  • Nothing is written to disk or cleaned up, which often makes this the clearest form in a test.

Checkpoint: run the class again. Two tests pass.

Build a Part With MultiPartSpecBuilder

Goal: set every detail of each part by name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void buildAPartWithMultiPartSpecBuilder() {
    paymentsApi()
        .multiPart(new MultiPartSpecBuilder("May salaries").controlName("batchName").build())
        .multiPart(new MultiPartSpecBuilder(CSV.getBytes(StandardCharsets.UTF_8))
                .controlName("file")
                .fileName("may.csv")
                .mimeType("text/csv")
                .build())
    .when()
        .post("/payments/bulk")
    .then()
        .statusCode(201)
        .body("fileName", equalTo("may.csv"));
}

What’s happening:

  • MultiPartSpecBuilder takes the content, then sets the control name, file name and MIME type with named methods.
  • It can also set a part’s charset and extra headers.
  • Each setting is explicit, which helps when an API is strict about one of them.

Checkpoint: run the class again. Three tests pass.

Check What REST Assured Sends

Send a Multipart Request to the Echo

Goal: prove that REST Assured set the multipart content type and a boundary.

1
2
3
4
5
6
7
8
9
10
@Test
void theRequestIsMultipartFormData() {
    paymentsApi()
        .multiPart("batchName", "June")
    .when()
        .post("/echo")
    .then()
        .body("contentType", startsWith("multipart/form-data"))
        .body("contentType", containsString("boundary="));
}

What’s happening:

  • The echo’s contentType shows a header such as multipart/form-data; boundary=eOAyzG3K_izXATQptaIOZ_oqUp7bZlt.
  • The server reads the boundary from the content type to split the body, so it must be there.
  • The echo’s body field shows the parts on the wire, each starting with the boundary:
1
2
3
4
5
6
--eOAyzG3K_izXATQptaIOZ_oqUp7bZlt
Content-Disposition: form-data; name="batchName"
Content-Type: text/plain

June
--eOAyzG3K_izXATQptaIOZ_oqUp7bZlt--

Checkpoint: run the class again. Four tests pass.

Don’t add a body(..) to a multipart request. A multipart request is its own body, and REST Assured drops the other one without a warning: body("{\"a\":1}") with one multiPart(..) sends only the part. Send every field as a part.

You don’t need to set the content type yourself. If you do, as in contentType("multipart/form-data"), REST Assured still adds the boundary.

Test a Request With a Missing Part

Leave Out the File

Goal: prove that the API rejects an upload without its file.

1
2
3
4
5
6
7
8
9
@Test
void aMissingPartIsRejected() {
    paymentsApi()
        .multiPart("batchName", "No file")
    .when()
        .post("/payments/bulk")
    .then()
        .statusCode(400);
}

What’s happening:

  • The request has only the batchName part, so the API answers 400 with the detail The part 'file' is missing.
  • A test like this proves that the API checks its input, instead of failing later with a less useful error.

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

Run the Tests

Run the following command from the repository root:

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

You should see a result similar to the following:

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

Make a Test Fail

In uploadBytesWithAFileName, change the control name of the file part from "file" to "csv" and run the command again. You should see a result similar to the following:

1
2
3
[ERROR] Failures:
[ERROR]   MultipartUploadTest.uploadBytesWithAFileName:81 1 expectation failed.
Expected status code <201> but was <400>.

The upload still carries the CSV, but under a name the server doesn’t look for, so it reports the file part as missing. A wrong control name gives the same 400 as a missing part. Add log().ifValidationFails() to see the problem details, which name the part.

Change the control name back to "file" and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
400 with The part 'file' is missingThe part is missing, or its control name is misspelledUse the exact control names file and batchName
400 with Each CSV line needs 5 fieldsA line of the CSV has the wrong number of fieldsCheck the CSV, or build it from a text block
fileContentType is application/octet-streamThe file part was added without a MIME typePass "text/csv" as the last argument to multiPart(..)
A JSON field never reaches the serverIt was sent with body(..) next to multiPart(..)Send it as a part instead

Try It Yourself

Exercise 1: Upload a Single Payment

Add a test called uploadASinglePayment that uploads a CSV with a header row and one line, NL91ABNA0417164300,NL69INGB0123456789,Jan Jansen,75.00,EUR, as single.csv with the batch name "Single payment". Check the status code, that count is 1 and that paymentIds has one entry.

Hint

Start from uploadBytesWithAFileName. Build the CSV in a local text block, with the same header row as the class’s CSV.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void uploadASinglePayment() {
    String oneLine = """
        debtorIban,creditorIban,creditorName,amount,currency
        NL91ABNA0417164300,NL69INGB0123456789,Jan Jansen,75.00,EUR
        """;

    paymentsApi()
        .multiPart("batchName", "Single payment")
        .multiPart("file", "single.csv", oneLine.getBytes(StandardCharsets.UTF_8), "text/csv")
    .when()
        .post("/payments/bulk")
    .then()
        .statusCode(201)
        .body("count", equalTo(1))
        .body("paymentIds", hasSize(1));
}

Exercise 2: Read Back an Uploaded Payment

Add a test called anUploadedPaymentCanBeReadBack. Upload the class’s CSV as june.csv with the batch name "June salaries", and extract the second id from paymentIds. Then read that payment with GET /payments/{id}, and check that it belongs to "Emily Clarke", has the amount "950.00", and has the batch name as its reference.

Hint

Use extract().path("paymentIds[1]") after the status check, as @BeforeEach did with extract().path("id") in Send Every HTTP Method in REST Assured. Indexes start at 0.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Test
void anUploadedPaymentCanBeReadBack() {
    String id = paymentsApi()
        .multiPart("batchName", "June salaries")
        .multiPart("file", "june.csv", CSV.getBytes(StandardCharsets.UTF_8), "text/csv")
    .when()
        .post("/payments/bulk")
    .then()
        .statusCode(201)
        .extract().path("paymentIds[1]");

    paymentsApi()
    .when()
        .get("/payments/{id}", id)
    .then()
        .statusCode(200)
        .body("creditorName", equalTo("Emily Clarke"))
        .body("amount", equalTo("950.00"))
        .body("reference", equalTo("June salaries"));
}

Summary

You built MultipartUploadTest, which uploads a CSV of payments with a batch name from a file, from bytes and with MultiPartSpecBuilder, shows the multipart envelope on the wire, and checks the rejection of an upload without its file. The payroll upload now has a test that sends what the form sends.

  • A multipart request is one body made of named parts, separated by a boundary.
  • multiPart(name, value) adds a text part, and multiPart(name, file, mimeType) adds a file part named after the file.
  • multiPart(name, fileName, bytes, mimeType) uploads content built in memory, and MultiPartSpecBuilder sets every detail of a part by name.
  • REST Assured sets multipart/form-data and the boundary for you, and drops any body(..) on a multipart request.
  • Test the upload, and test the request with a part missing or misnamed.

Here are the commands you used in this guide:

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

What’s Next

Next: you’ve completed Module 2. Continue with Module 3: Validating Responses in Depth, starting with Filter JSON Lists With GPath in REST Assured, which filters and transforms lists in a response with Groovy closures.

The code:

Go deeper:

Related guides:

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