Quarkus - Using the REST Client with Multipart

Resteasy has rich support for the multipart/* and multipart/form-data mime types. The multipart mime format is used to pass lists of content bodies. Multiple content bodies are embedded in one message. multipart/form-data is often found in web application HTML Form documents and is generally used to upload files. The form-data format is the same as other multipart formats, except that each inlined piece of content has a name associated with it.

This guide explains how to use the MicroProfile REST Client with Multipart in order to interact with REST APIsrequiring multipart/form-data content-type with very little effort.

Prerequisites

To complete this guide, you need:

  • less than 15 minutes

  • an IDE

  • JDK 1.8+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.5.3+

Solution

We recommend that you follow the instructions in the next sections and create the application step by step.However, you can go right to the completed example.

Clone the Git repository: git clone https://github.com/quarkusio/quarkus-quickstarts.git, or download an archive.

The solution is located in the rest-client-multipart-quickstart directory.

Creating the Maven project

First, we need a new project. Create a new project with the following command:

  1. mvn io.quarkus:quarkus-maven-plugin:1.0.0.CR1:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=rest-client-multipart-quickstart \
  4. -DclassName="org.acme.restclient.multipart.MultipartClientResource" \
  5. -Dpath="/client" \
  6. -Dextensions="rest-client, resteasy"
  7. cd rest-client-multipart-quickstart

This command generates the Maven project with a REST endpoint and imports the rest-client and resteasy extensions.

Then, we’ll add the following dependency to support multipart/form-data requests:

  1. <dependency>
  2. <groupId>org.jboss.resteasy</groupId>
  3. <artifactId>resteasy-multipart-provider</artifactId>
  4. </dependency>

Setting up the model

In this guide we will be demonstrating how to invoke a REST service accepting multipart/form-data input.We are assuming the payload is well-known before the request is sent, so we can model as a POJO.

If the payload is unknown, you can also use the RESTEasy custom API instead. If that’s the case, see the RESTEasy Multipart Providers link in the end of the guide.

Our first order of business is to setup the model we will be using to define the multipart/form-data payload, in the form of a MultipartBody POJO.

Create a src/main/java/org/acme/restclient/multipart/MultipartBody.java file and set the following content:

  1. package org.acme.restclient.multipart;
  2. import java.io.InputStream;
  3. import javax.ws.rs.FormParam;
  4. import javax.ws.rs.core.MediaType;
  5. import org.jboss.resteasy.annotations.providers.multipart.PartType;
  6. public class MultipartBody {
  7. @FormParam("file")
  8. @PartType(MediaType.APPLICATION_OCTET_STREAM)
  9. public InputStream file;
  10. @FormParam("fileName")
  11. @PartType(MediaType.TEXT_PLAIN)
  12. public String fileName;
  13. }

The purpose of the annotations in the code above is the following:

  • @FormParam is a standard JAX-RS annotation used to define a form parameter contained within a request entity body

  • @PartType is a RESTEasy specific annotation required when a client performs a multipart request and defines the content type for the part.

Create the interface

Using the MicroProfile REST Client is as simple as creating an interface using the proper JAX-RS and MicroProfile annotations. In our case the interface should be created at src/main/java/org/acme/restclient/multipart/MultipartService.java and have the following content:

  1. package org.acme.restclient.multipart;
  2. import javax.ws.rs.Consumes;
  3. import javax.ws.rs.POST;
  4. import javax.ws.rs.Path;
  5. import javax.ws.rs.Produces;
  6. import javax.ws.rs.core.MediaType;
  7. import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
  8. import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
  9. @Path("/echo")
  10. @RegisterRestClient
  11. public interface MultipartService {
  12. @POST
  13. @Consumes(MediaType.MULTIPART_FORM_DATA)
  14. @Produces(MediaType.TEXT_PLAIN)
  15. String sendMultipartData(@MultipartForm MultipartBody data);
  16. }

The sendMultipartData method gives our code the ability to POST a multipart/form-data request to our Echo service (running in the same server for demo purposes).Because in this demo we have the exact knowledge of the multipart/form-data packets, we can map them to the model class created in the previous section using the @org.jboss.resteasy.annotations.providers.multipart.MultipartForm annotation.

The client will handle all the networking and marshalling leaving our code clean of such technical details.

The purpose of the annotations in the code above is the following:

  • @RegisterRestClient allows Quarkus to know that this interface is meant to be available forCDI injection as a REST Client

  • @Path, @GET and @PathParam are the standard JAX-RS annotations used to define how to access the service

  • @MultipartForm defines the parameter as a value object for incoming/outgoing request/responses of the multipart/form-data mime type.

  • @Consumes defines the expected content-type consumed by this request (parameters)

  • @Produces defines the expected content-type produced by this request (return type)

While @Consumes and @Produces are optional as auto-negotiation is supported,it is heavily recommended to annotate your endpoints with them to define precisely the expected content-types.It will allow to narrow down the number of JAX-RS providers (which can be seen as converters) included in the native executable.

Create the configuration

In order to determine the base URL to which REST calls will be made, the REST Client uses configuration from application.properties.The name of the property needs to follow a certain convention which is best displayed in the following code:

  1. # Your configuration properties
  2. org.acme.restclient.multipart.MultipartService/mp-rest/url=http://localhost:8080/

Having this configuration means that all requests performed using org.acme.restclient.multipart.MultipartService will use http://localhost:8080/ as the base URL.

Note that org.acme.restclient.multipart.MultipartService must match the fully qualified name of the MultipartService interface we created in the previous section.

Update the JAX-RS resource

Open the src/main/java/org/acme/restclient/multipart/MultipartClientResource.java file and update it with the following content:

  1. package org.acme.restclient.multipart;
  2. import java.io.ByteArrayInputStream;
  3. import javax.inject.Inject;
  4. import javax.ws.rs.POST;
  5. import javax.ws.rs.Path;
  6. import javax.ws.rs.Produces;
  7. import javax.ws.rs.core.MediaType;
  8. import org.eclipse.microprofile.rest.client.inject.RestClient;
  9. @Path("/client")
  10. public class MultipartClientResource {
  11. @Inject
  12. @RestClient
  13. MultipartService service;
  14. @POST
  15. @Path("/multipart")
  16. @Produces(MediaType.TEXT_PLAIN)
  17. public String sendFile() throws Exception {
  18. MultipartBody body = new MultipartBody();
  19. body.fileName = "greeting.txt";
  20. body.file = new ByteArrayInputStream("HELLO WORLD".getBytes());
  21. return service.sendMultipartData(body);
  22. }
  23. }

Note that in addition to the standard CDI @Inject annotation, we also need to use the MicroProfile @RestClient annotation to inject MultipartService.

Creating the server

For demo purposes, let’s create a simple Echo endpoint that will act as the server part.

Create the directory src/main/java/org/acme/restclient/multipart/server and include a EchoService.java file with the following content:

  1. package org.acme.restclient.multipart.server;
  2. import javax.ws.rs.Consumes;
  3. import javax.ws.rs.POST;
  4. import javax.ws.rs.Path;
  5. import javax.ws.rs.Produces;
  6. import javax.ws.rs.core.MediaType;
  7. @Path("/echo")
  8. public class EchoService {
  9. @POST
  10. @Consumes(MediaType.MULTIPART_FORM_DATA)
  11. @Produces(MediaType.TEXT_PLAIN)
  12. public String echo(String requestBody) throws Exception {
  13. return requestBody;
  14. }
  15. }

This will just return the request body and it’s useful for testing purposes.

Update the test

We also need to update the functional test to reflect the changes made to the endpoint.Edit the src/test/java/org/acme/restclient/multipart/MultipartResourceTest.java file to:

  1. package org.acme.restclient.multipart;
  2. import io.quarkus.test.junit.QuarkusTest;
  3. import org.junit.jupiter.api.Test;
  4. import static io.restassured.RestAssured.given;
  5. import static org.hamcrest.CoreMatchers.containsString;
  6. @QuarkusTest
  7. public class MultipartResourceTest {
  8. @Test
  9. public void testMultipartDataIsSent() {
  10. given()
  11. .when().post("/client/multipart")
  12. .then()
  13. .statusCode(200)
  14. .body( containsString("Content-Disposition: form-data; name=\"file\""),
  15. containsString("HELLO WORLD"),
  16. containsString("Content-Disposition: form-data; name=\"fileName\""),
  17. containsString("greeting.txt"));
  18. }
  19. }

The code above uses REST Assured to assert that the returned content from the echo service contains multipart elements

Because the test runs in a different port, we also need to include an application.properties in our src/test/resources with the following content:

  1. # Your configuration properties
  2. org.acme.restclient.multipart.MultipartService/mp-rest/url=http://localhost:8081/

Package and run the application

You should see an output similar to:

  1. --89d288bd-960f-460c-b266-64c5b4d170fa
  2. Content-Disposition: form-data; name="fileName"
  3. Content-Type: text/plain
  4. greeting.txt
  5. --89d288bd-960f-460c-b266-64c5b4d170fa
  6. Content-Disposition: form-data; name="file"
  7. Content-Type: application/octet-stream
  8. HELLO WORLD
  9. --89d288bd-960f-460c-b266-64c5b4d170fa--

As usual, the application can be packaged using ./mvnw clean package and executed using the -runner.jar file.You can also generate the native executable with ./mvnw clean package -Pnative.

Further reading