How to Consume REST API in Quarkus
Hello everyone, today, we will learn how to consume REST API in Quarkus. Making HTTP requests is a core feature of programming, and is often one of the first things you want to do when learning new technology. For Java programmers, there are many ways to do it - core libraries in the JDK and third-party libraries.
Here, we will learn how to use the below technologies to consume REST API in Quarkus.
- MP Rest Client
- JAX-RS Client
- ApacheHttpClient
- Java 11 HttpClient
Related topics,
- Create Quarkus Project With code.quarkus.io
- Quarkus + Angular 10 + MongoDB CRUD Example
- Quarkus + React JS + MongoDB CRUD Example
- Quarkus + Vue.js + MongoDB CRUD Example
The source code download link is provided at the end of this tutorial.
Project Directory:
Maven Dependencies[pom.xml].
<?xml version="1.0"?><project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0https://maven.apache.org/xsd/maven-4.0.0.xsd"xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><modelVersion>4.0.0</modelVersion><groupId>org.knf.dev.demo</groupId><artifactId>quarku-consume-restful-service</artifactId><version>1.0.0-SNAPSHOT</version><properties><compiler-plugin.version>3.8.1</compiler-plugin.version><failsafe.useModulePath>false</failsafe.useModulePath><maven.compiler.release>17</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><quarkus.platform.artifact-id>quarkus-bom</quarkus.platform.artifact-id><quarkus.platform.group-id>io.quarkus.platform</quarkus.platform.group-id><quarkus.platform.version>2.7.3.Final</quarkus.platform.version><surefire-plugin.version>3.0.0-M5</surefire-plugin.version></properties><dependencyManagement><dependencies><dependency><groupId>${quarkus.platform.group-id}</groupId><artifactId>${quarkus.platform.artifact-id}</artifactId><version>${quarkus.platform.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><dependency><groupId>io.quarkus</groupId><artifactId>quarkus-rest-client</artifactId></dependency><dependency><groupId>io.quarkus</groupId><artifactId>quarkus-rest-client-jackson</artifactId></dependency><dependency><groupId>io.quarkus</groupId><artifactId>quarkus-apache-httpclient</artifactId></dependency><dependency><groupId>io.quarkus</groupId><artifactId>quarkus-arc</artifactId></dependency><dependency><groupId>io.quarkus</groupId><artifactId>quarkus-resteasy</artifactId></dependency><dependency><groupId>io.quarkus</groupId><artifactId>quarkus-junit5</artifactId><scope>test</scope></dependency><dependency><groupId>io.rest-assured</groupId><artifactId>rest-assured</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>${quarkus.platform.group-id}</groupId><artifactId>quarkus-maven-plugin</artifactId><version>${quarkus.platform.version}</version><extensions>true</extensions><executions><execution><goals><goal>build</goal><goal>generate-code</goal><goal>generate-code-tests</goal></goals></execution></executions></plugin><plugin><artifactId>maven-compiler-plugin</artifactId><version>${compiler-plugin.version}</version><configuration><compilerArgs><arg>-parameters</arg></compilerArgs></configuration></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>${surefire-plugin.version}</version><configuration><systemPropertyVariables><java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager><maven.home>${maven.home}</maven.home></systemPropertyVariables></configuration></plugin></plugins></build><profiles><profile><id>native</id><activation><property><name>native</name></property></activation><build><plugins><plugin><artifactId>maven-failsafe-plugin</artifactId><version>${surefire-plugin.version}</version><executions><execution><goals><goal>integration-test</goal><goal>verify</goal></goals><configuration><systemPropertyVariables><native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path><java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager><maven.home>${maven.home}</maven.home></systemPropertyVariables></configuration></execution></executions></plugin></plugins></build><properties><quarkus.package.type>native</quarkus.package.type></properties></profile></profiles></project>
Create a Post POJO class:
package org.knf.dev.demo.model;public class Post {private String userId;private String id;private String body;private String title;public String getUserId() {return userId;}public void setUserId(String userId) {this.userId = userId;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getBody() {return body;}public void setBody(String body) {this.body = body;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public Post() {}public Post(String userId,String id, String body, String title) {this.userId = userId;this.id = id;this.body = body;this.title = title;}}
Method 1. How to use MicroProfile Rest Client to consume REST APIs.
Create PostService:
package org.knf.dev.demo.mprestclientdemo;import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;import org.knf.dev.demo.model.Post;import javax.ws.rs.GET;import javax.ws.rs.Path;import java.util.List;@Path("/posts")/*@RegisterRestClient allows Quarkus to knowthat this interface is meant to be available forCDI injection as a REST Client*/@RegisterRestClientpublic interface PostService {@GETList<Post> fetchAllPosts();}
Configure the base URL in application.properties
org.knf.dev.demo.mprestclientdemo.PostService/mp-rest/url = https://jsonplaceholder.typicode.com
Create PostResource
package org.knf.dev.demo.mprestclientdemo;import org.eclipse.microprofile.rest.client.inject.RestClient;import org.knf.dev.demo.model.Post;import javax.inject.Inject;import javax.ws.rs.GET;import javax.ws.rs.Path;import java.util.List;@Path("/api/v1/mprestclient")public class PostResource {@Inject@RestClientPostService postService;@GET@Path("/posts")public List<Post> fetchAllPosts() {return postService.fetchAllPosts();}}
Method 2. How to use ApacheHttpClient to consume REST APIs.
Create HttpService
package org.knf.dev.demo.apachehttpclient;import com.fasterxml.jackson.databind.ObjectMapper;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.knf.dev.demo.model.Post;import javax.inject.Singleton;import java.io.IOException;import java.util.List;@Singletonpublic class HttpService {CloseableHttpClient httpClient = HttpClients.createDefault();public <T> List<T> fetchPosts(String url, Class<Post> responseType)throws IOException {HttpGet request = new HttpGet(url);request.addHeader("content-type", "application/json");CloseableHttpResponse response = httpClient.execute(request);ObjectMapper objectMapper =new ObjectMapper();return objectMapper.readValue(response.getEntity().getContent(),objectMapper.getTypeFactory().constructCollectionType(List.class, responseType));}}
Create PostResource
package org.knf.dev.demo.apachehttpclient;import org.knf.dev.demo.model.Post;import javax.inject.Inject;import javax.ws.rs.GET;import javax.ws.rs.Path;import java.io.IOException;import java.util.List;@Path("/api/v1/apachehttpclient")public class PostResource {@InjectHttpService httpService;@GET@Path("/posts")public List<Post> fetchAllPosts()throws IOException, InterruptedException {List<Post> posts = httpService.fetchPosts("https://jsonplaceholder.typicode.com/posts",Post.class);return posts;}}
Method 3. How to use Java 11 HttpClient to consume REST APIs.
Create HttpService
package org.knf.dev.demo.newhttpclientdemo;import com.fasterxml.jackson.databind.ObjectMapper;import javax.inject.Singleton;import java.io.IOException;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.util.List;@Singletonpublic class HttpService {private final HttpClient httpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build();public <T> List<T> fetchPosts(String url, Class<T> responseType)throws InterruptedException, IOException {HttpRequest request = HttpRequest.newBuilder().GET().uri(URI.create(url)).header("Accept","application/json").build();HttpResponse<String> response =httpClient.send(request, HttpResponse.BodyHandlers.ofString());ObjectMapper objectMapper =new ObjectMapper();return objectMapper.readValue(response.body(),objectMapper.getTypeFactory().constructCollectionType(List.class, responseType));}}
Create PostResource
package org.knf.dev.demo.newhttpclientdemo;import java.io.IOException;import java.util.List;import javax.inject.Inject;import javax.ws.rs.GET;import javax.ws.rs.Path;import org.knf.dev.demo.model.Post;@Path("/api/v1/httpclient")public class PostResource {@InjectHttpService httpService;@GET@Path("/posts")public List<Post> fetchAllPosts()throws IOException, InterruptedException {HttpService httpService = new HttpService();List<Post> posts = httpService.fetchPosts("https://jsonplaceholder.typicode.com/posts",Post.class);return posts;}}
Method 4. How to use JAX-RS Client to consume REST APIs.
Create PostResource
package org.knf.dev.demo.jaxrsclientdemo;import org.knf.dev.demo.model.Post;import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.client.Client;import javax.ws.rs.client.ClientBuilder;import javax.ws.rs.core.GenericType;import java.util.List;@Path("/api/v1/jaxrsclient")public class PostResource {private final Client client =ClientBuilder.newBuilder().build();private final String url ="https://jsonplaceholder.typicode.com/posts";@GET@Path("/posts")public List<Post> fetchAllPosts() {List<Post> posts = client.target(url).request().get(new GenericType<List<Post>>() {});return posts;}}
Run the Quarkus Application
Build application jar file: mvn clean package
Start the application: java -jar quarkus-run.jar
Test Case 1: Use ApacheHttpClient to consume REST APIs.
Test Case 2: Use JAX-RS Client to consume REST APIs.
Test Case 3: Use MicroProfile Rest Client to consume REST APIs.
Test Case 4: Use Java 11 HttpClient to consume REST APIs.
More related topics,