Post multipart file and JSON in Rest Assured

Infant Anto Rodrigo picture Infant Anto Rodrigo · Jan 8, 2018 · Viewed 11.1k times · Source

I need to send a video file and JSON object in Rest Assured post call.

Structure is like the following:

{ "sample" : { "name" : "sample-name", "kind" : "upload", "video_file" : multipart file here } }

So I did like the following

Code:

given()
                        .header("Accept", "application/json")
                        .header(auth)
                        .config(rConfig)
                        .body(body)
                        .multiPart("sample[video_file]", new File("path"), "video/mp4")
                        .formParam("sample[name]", "Video Upload")
                        .formParam("sample[kind]", "upload")
                        .log().all().
                        expect()
                        .statusCode(expectedStatusCode)
                        .post(url);

I can't use application/JSON while using multipart in Rest Assured. I explicitly hardcoded the value in the form param and sent the media file in multipart and now it is working fine.

How can I send all the form param data in a single inner object.

Answer

rohit.jaryal picture rohit.jaryal · Jan 10, 2018

You can do this by using RequestSpecBuilder. It supports all the request parameters and you can easily create multipart request.

Sample code taken from https://github.com/rest-assured/rest-assured/wiki/Usage

RequestSpecBuilder builder = new RequestSpecBuilder();
builder.addParam("parameter1", "parameterValue");
builder.addHeader("header1", "headerValue");
RequestSpecification requestSpec = builder.build();

given().
        spec(requestSpec).
        param("parameter2", "paramValue").
when().
        get("/something").
then().
        body("x.y.z", equalTo("something"));