Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท REST Endpoints

REST Client and Filters

Call other HTTP services from Quarkus with the type-safe REST Client, add request and response filters, and protect calls with timeouts, retries and fallbacks.

Most services also call other services. Quarkus gives you a type-safe REST client: you write a Java interface, annotate it like a resource, and Quarkus generates the implementation. Around both the server and the client you can add filters, small pieces of code that run before or after each request. This lesson covers both, plus the fault-tolerance annotations that keep a slow neighbour from taking you down.

The real Quarkus code is read-only. The stand-ins build a miniature client with a Java dynamic proxy and a filter chain, which is close to how the real thing works conceptually.

The REST Client

Add quarkus-rest-client-jackson (it brings JSON support). Then describe the remote API as an interface:

Java
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
import jakarta.ws.rs.*;
import java.util.List;

@RegisterRestClient(configKey = "isbn-api")
@Path("/v1")
public interface IsbnService {

    @GET
    @Path("/books/{isbn}")
    IsbnInfo lookup(@PathParam("isbn") String isbn);

    @GET
    @Path("/books")
    List<IsbnInfo> search(@QueryParam("q") String query, @QueryParam("limit") int limit);
}

public record IsbnInfo(String isbn, String title, int pages) {}

The base URL is configuration, not code:

PROPERTIES
quarkus.rest-client.isbn-api.url=https://isbn.example.com
quarkus.rest-client.isbn-api.connect-timeout=2000
quarkus.rest-client.isbn-api.read-timeout=5000

Inject the interface with @RestClient anywhere:

Java
import org.eclipse.microprofile.rest.client.inject.RestClient;

@ApplicationScoped
public class CatalogueService {

    @Inject
    @RestClient
    IsbnService isbn;

    public int pagesOf(String code) {
        return isbn.lookup(code).pages();
    }
}

Return types can be plain objects, RestResponse<T> (to read status and headers) or Uni<T> for non-blocking calls. A response with status 400 or above throws a WebApplicationException unless you add a @ClientExceptionMapper:

Java
@ClientExceptionMapper
static RuntimeException toException(Response response) {
    if (response.getStatus() == 404) {
        return new BookNotFound(response.getHeaderString("X-Missing-Id"));
    }
    return null; // let the default handling run
}

Place the method inside the client interface. Returning null means "I do not handle this one."

Headers and authentication

Use @ClientHeaderParam for fixed headers, or @HeaderParam for dynamic ones:

Java
@ClientHeaderParam(name = "X-Client", value = "bookshop")
@ClientHeaderParam(name = "Authorization", value = "Bearer {token}")
String secured();
default String token() { return System.getenv("ISBN_TOKEN"); }

A client from an interface, modelled

How can an interface with no implementation answer calls? Quarkus generates a class at build time. A plain Java program can do the same job at run time with java.lang.reflect.Proxy. The stand-in reads our own @Get annotation, fills in the path template and sends the request to a fake transport instead of a real network.

Java Stand-in: a type-safe client built with a Proxy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The method signature is the contract: change the interface and the "client" changes with it, and the compiler tells you everywhere it is used.

Filters

A filter runs around the request or the response. Quarkus REST offers simple annotations:

Java
import org.jboss.resteasy.reactive.server.ServerRequestFilter;
import org.jboss.resteasy.reactive.server.ServerResponseFilter;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;

public class Filters {

    @ServerRequestFilter
    public void requestId(ContainerRequestContext ctx) {
        if (ctx.getHeaderString("X-Request-Id") == null) {
            ctx.getHeaders().add("X-Request-Id", java.util.UUID.randomUUID().toString());
        }
    }

    @ServerRequestFilter(preMatching = true)
    public void lowercasePath(ContainerRequestContext ctx) {
        // runs before the endpoint is chosen
    }

    @ServerResponseFilter
    public void addHeaders(ContainerResponseContext res) {
        res.getHeaders().add("X-Served-By", "bookshop");
    }
}

A request filter can also abort the request by returning a RestResponse (for example a 401), in which case the endpoint never runs. @ServerRequestFilter(priority = ...) controls ordering. For the client side, use @ClientRequestFilter / @ClientResponseFilter classes registered with @RegisterProvider on the interface.

Filters versus interceptors

CDI interceptors wrap Java method calls on beans. Filters wrap HTTP requests. Use a filter for headers, authentication, request IDs and access logs; use an interceptor for business logic such as transactions or auditing.

Java Stand-in: a request filter chain that can abort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Fault tolerance for outgoing calls

Remote calls fail. Add the quarkus-smallrye-fault-tolerance extension and use MicroProfile annotations on any bean method, including one that calls a REST client:

Java
@Timeout(2000)
@Retry(maxRetries = 3, delay = 200, jitter = 100)
@CircuitBreaker(requestVolumeThreshold = 8, failureRatio = 0.5, delay = 5000)
@Fallback(fallbackMethod = "cachedPages")
public int pagesOf(String code) {
    return isbn.lookup(code).pages();
}

int cachedPages(String code) {
    return cache.getOrDefault(code, -1);
}
  • @Timeout gives up after the given milliseconds.
  • @Retry repeats the call (with a delay) for transient failures.
  • @CircuitBreaker stops calling a failing service for a while so it can recover.
  • @Fallback returns a safe substitute when everything else fails.

Only retry calls that are safe to repeat, such as GET. Retrying a POST that charges a card can charge twice.

Calling other services

Interface Describe the remote API in Java.
Config The URL lives in properties.
Inject @RestClient gives you an object.

The generated client does the HTTP work.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you provide the base URL of a REST client declared with configKey = "isbn-api"?

    The config key maps to quarkus.rest-client.<key>.url, so the URL can change per environment.
  2. 2. What injects a REST client interface into a bean?

    The @RestClient qualifier selects the generated REST client bean.
  3. 3. What can a request filter do that an endpoint cannot?

    A request filter runs before the endpoint and may return its own response to stop processing.
  4. 4. Which fault-tolerance annotation stops calling a service that keeps failing, to let it recover?

    A circuit breaker opens after repeated failures and rejects calls for a while.

Summary

  • A REST client is an annotated interface with @RegisterRestClient; its URL comes from quarkus.rest-client.<key>.url.
  • Inject it with @RestClient; use @ClientExceptionMapper for custom error handling.
  • Filters (@ServerRequestFilter, @ServerResponseFilter) wrap HTTP requests and can abort them.
  • Fault tolerance annotations (@Timeout, @Retry, @CircuitBreaker, @Fallback) protect remote calls.

Next: OpenAPI and Swagger UI