Skip to content
javahacks.dev
Quarkus

How to Use the Quarkus REST Client for Outbound HTTP Calls

Call other HTTP services from Quarkus with the REST Client: an annotated interface, configuration, headers, error mapping, timeouts and testing with mocks.

6 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Spring, Swagger, NGINX and Spring Boot logos.

Writing HTTP calls by hand means writing the same four things in every service: build the URL, set the headers, serialize the body, and turn a bad status into something your code can handle. The Quarkus REST Client moves all four into a Java interface, so a call to another service reads like a call to a bean. This post uses Quarkus 3 on Java 25 and covers configuration, headers, errors, timeouts and tests. The server side is in Quarkus REST.

Add the extension

The client needs two dependencies: the REST client itself and its Jackson binding.

XML
<dependency>
  <groupId>io.quarkus</groupId>
  <artifactId>quarkus-rest-client</artifactId>
</dependency>
<dependency>
  <groupId>io.quarkus</groupId>
  <artifactId>quarkus-rest-client-jackson</artifactId>
</dependency>

Without the Jackson artifact the build succeeds and the first call fails at runtime, with a message that it cannot find a MessageBodyReader for your type. That is the most common first-run failure, and the fix is the second dependency.

Declare the remote API as an interface

src/main/java/com/example/PriceClient.javajava
@RegisterRestClient(configKey = "prices")
@Path("/prices")
public interface PriceClient {

    @GET
    @Path("/{sku}")
    Price get(@PathParam("sku") String sku, @HeaderParam("X-Trace") String trace);

    @GET
    Uni<List<Price>> all(@QueryParam("category") String category);
}

The annotations are the standard Jakarta REST ones, the same you use to write a resource. @RegisterRestClient makes the interface a bean, and configKey is the name its settings live under.

properties
quarkus.rest-client.prices.url=https://prices.internal.example.com
quarkus.rest-client.prices.connect-timeout=2000
quarkus.rest-client.prices.read-timeout=5000

Keep the URL out of the annotation. A hard-coded baseUri works until the first staging environment, and then every build needs a different jar. The property can change per environment through the usual profile prefixes, such as %prod.quarkus.rest-client.prices.url.

Inject it and call it

java
@Path("/quote")
public class QuoteResource {

    @RestClient
    PriceClient prices;

    @GET
    @Path("/{sku}")
    public Price quote(@PathParam("sku") String sku) {
        return prices.get(sku, UUID.randomUUID().toString());
    }
}

@RestClient is the qualifier that selects the generated client. Forgetting it gives you an unsatisfied dependency error at build time, which is the friendlier of the two failures because it arrives before deployment.

A method that returns Price blocks the calling thread until the response arrives. That is fine on a worker thread, and a resource method that returns a plain object runs on one. A method that returns Uni is non-blocking and belongs in event-loop code. The rule to keep is simple: never call the blocking variant from inside a Uni pipeline running on the event loop, or Quarkus will warn you that you blocked it, and under load the application stalls.

Headers and authentication

For a header that every call needs, annotate the interface with @ClientHeaderParam:

java
@ClientHeaderParam(name = "X-Client", value = "quote-service")
public interface PriceClient { /* ... */ }

For a header that comes from the incoming request, such as a trace ID or an Authorization token you want to pass along, implement ClientHeadersFactory and register it with @RegisterClientHeaders. Forwarding is opt-in on purpose. Copying every inbound header to an outbound call would leak cookies to a third party.

For OAuth 2 bearer tokens, the OIDC client extension attaches a token automatically and refreshes it before expiry. It pairs with the server side in Quarkus OIDC.

Turning status codes into exceptions

By default a 4xx or 5xx response throws WebApplicationException, and the caller has to inspect getResponse().getStatus(). A mapper turns a status you care about into a domain exception:

java
@ClientExceptionMapper
static RuntimeException toException(Response response) {
    if (response.getStatus() == 404) {
        return new PriceNotFound();
    }
    return null;
}

Declare it as a static method on the interface. Returning null hands the response to the next mapper and finally to the default behavior, so you only handle the codes that mean something to you. A common mistake is to return an exception for every status, including 200 with an empty body. Check the status first.

Timeouts are not optional

The defaults suit nobody. A connect timeout that is too long holds a worker thread while the network drops packets, and a missing read timeout lets one slow dependency drain every thread in the pool. Set both, as in the properties above, and set them from the dependency's real latency rather than from a guess. If the remote service answers in 50 milliseconds at the 99th percentile, a read timeout of five seconds is generous, and one of 30 seconds is a bug waiting for an outage.

The symptoms of missing timeouts, and how to find the call that is hanging, are in debugging Java client timeouts.

Sending a body and reading a list

Request and response bodies are plain Java types. A POST that takes a record and returns the created resource looks like this:

java
@POST
@Consumes(MediaType.APPLICATION_JSON)
Price create(NewPrice body);

Jackson serializes the argument and reads the reply, so a field renamed on the server side shows up as a null on yours rather than as an error. When you need the status or the headers as well as the body, return jakarta.ws.rs.core.Response and read them yourself. It costs you the typed result, so use it only for the calls that need a Location header or an ETag.

A list is returned as List<Price>, and a very large list is better fetched in pages than in one response. Ask the remote API for a page size and loop, instead of raising the read timeout until a ten thousand row reply happens to fit.

Retries and circuit breakers

A remote call fails, slows or hangs. Add @Timeout, @Retry and @CircuitBreaker from SmallRye Fault Tolerance to the method that calls the client. Two rules keep this safe. Retry only operations that are idempotent, because retrying a POST that charged a card is how a customer is charged twice. And keep the client timeout shorter than the total fault tolerance timeout, or the outer timeout fires first and hides the real error.

Testing the caller

Replace the client with a mock bean so a test needs no network:

java
@QuarkusTest
class QuoteResourceTest {

    @InjectMock
    @RestClient
    PriceClient prices;

    @Test
    void returnsQuote() {
        Mockito.when(prices.get(eq("A-1"), any()))
            .thenReturn(new Price("A-1", BigDecimal.TEN));

        given().get("/quote/A-1").then().statusCode(200);
    }
}

This tests your resource and nothing about the wire format. To test serialization, headers and error mapping, point the client at a real HTTP server with WireMock through the quarkus-wiremock test support, and assert on the requests it received. Mocking and WireMock answer different questions, and a service that depends on a third party deserves both. The mocking details are in mocking beans in Quarkus tests.

Where the REST Client is the wrong tool

For a single call in one place, the JDK HttpClient has no setup and no extension to maintain. The interface pays off when several classes call the same API, because the contract lives in one file. It also fits poorly with APIs that are not REST-shaped, such as streaming uploads with unusual framing, where you will fight the abstraction. The full option list is in the Quarkus REST client guide, and the underlying contract is the MicroProfile REST Client specification.

Also inSpring MVC
Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.