Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Using the JAX-RS client API, write code that calls GET https://inventory/api/items/{sku} with a bearer token, returns an Item, and treats 404 as Optional.empty(). What resources must you close and why?

We build one Client with ClientBuilder.newBuilder().connectTimeout(...).readTimeout(...).build() and reuse it, because it is expensive to create and safe to share. Each call does client.target(base).path("items/{sku}").resolveTemplate("sku", sku).request(MediaType.APPLICATION_JSON).header("Authorization", "Bearer " + token).get() inside try-with-resources, returning Optional.empty() for 404 and Optional.of(r.readEntity(Item.class)) otherwise. We must close every Response, because an unread or unclosed response keeps its connection out of the pool and leaks connections under load, and we close the Client when the application shuts down; calling get(Item.class) instead throws NotFoundException for 404, which is an alternative style.

Why this question is asked

Calling another HTTP service is something every backend does, and the JAX-RS client API is standard across Jersey, RESTEasy and the MicroProfile runtimes. The code is short, but it hides two production problems: services that create a new Client per call, and responses that are never closed, which slowly exhaust the connection pool until every request times out. Interviewers ask this to check both the API and the resource handling. In this answer, we will recap the main client classes, write the lookup method, see exactly why responses must be closed, compare the typed get(Item.class) style, and add the token to every request with a filter.

1A Quick Recap of the Client API

The JAX-RS client API has three main types. A Client is the heavy object: it holds the connection pool, the TLS setup, timeouts and registered providers such as the JSON reader. A WebTarget is an immutable description of a URL, built from the client with target(...) and extended with path(...), query parameters and template values. A Response is the result of one call: status, headers and an entity stream that we can read once.

Because Client is expensive to build and, in the common implementations, safe to use from many threads, we create one per remote service, typically when the application starts, and reuse it for every request. Creating a client per call throws away the connection pool every time and can leak resources if the client is not closed.

2Writing the Lookup

Here is a small client class for the inventory service.

Java
public class InventoryClient implements AutoCloseable {
private final Client client;
private final WebTarget item;
public InventoryClient(URI baseUri) {
this.client = ClientBuilder.newBuilder()
.connectTimeout(2, TimeUnit.SECONDS) // fail fast if the host is down
.readTimeout(5, TimeUnit.SECONDS) // do not wait forever for a slow reply
.build();
this.item = client.target(baseUri).path("items/{sku}"); // https://inventory/api/items/{sku}
}
public Optional<Item> find(String sku, String token) {
try (Response r = item.resolveTemplate("sku", sku) // value is URL-encoded
.request(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
.get()) {
if (r.getStatus() == 404) return Optional.empty(); // Optional.empty, connection released
if (r.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
throw new InventoryException("inventory returned " + r.getStatus());
}
return Optional.of(r.readEntity(Item.class)); // Optional[Item[sku=AB-1, stock=7]]
}
}
@Override
public void close() { client.close(); } // at application shutdown
}
// new InventoryClient(URI.create("https://inventory/api")).find("AB-1", token)

Notice the order of checks. 404 is a normal outcome for this method, so it becomes an empty Optional. Other non-2xx statuses, such as 401 or 503, are real failures and become an exception, which the caller can retry or report. Only a successful response is read as an Item, using the JSON provider registered with the client.

3Why Every Response Must Be Closed

With a pooling connector, a connection is leased from the pool when the request is sent and returned when the response body has been fully read or the Response is closed. readEntity reads the body and usually releases the connection, but on the paths where we do not read the body, such as the 404 branch or an exception thrown before reading, the connection stays leased unless we close the Response.

So without try-with-resources, every 404 leaks one connection. With a pool of, say, 20 connections per host, the 21st request waits for a free connection, times out or blocks, and the service seems to hang even though the inventory service is healthy. The try-with-resources block closes the Response on every path, including exceptions, which is why Response implements AutoCloseable.

Step throughA connection's life during one call
  1. get() leases a pooled connectionPool of 20 per host
  2. Body read fully or Response closed?
    YesConnection returned to the poolNoConnection stays leased
  3. Leaks add up under loadEvery unclosed 404 or error
  4. Pool exhaustedNew calls wait, then time out

4 steps in order. Play them, or step through them one at a time.

4The Alternative: Typed get(Item.class)

The invocation builder can also read the entity directly with get(Item.class). In that style, the runtime reads and closes the response for us on success, and throws a WebApplicationException subclass for non-2xx statuses: NotFoundException for 404, NotAuthorizedException for 401 and so on.

Java
public Optional<Item> find(String sku, String token) {
try {
return Optional.of(item.resolveTemplate("sku", sku)
.request(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
.get(Item.class)); // Item on 2xx
} catch (NotFoundException e) {
return Optional.empty(); // 404
}
// ProcessingException for timeouts and connection errors
}

This is shorter and handles closing automatically, but it uses exceptions for a normal outcome, and the exception's response may still hold the body that we did not read. Both styles are fine; the explicit Response style gives more control over headers and statuses, which is why many teams prefer it for anything beyond simple calls.

5Follow-up questions

How do you add the token for every request without repeating code?

Register a ClientRequestFilter on the Client. It runs before every request sent through that client, so it can set the header in one place, for example client.register((ClientRequestFilter) ctx -> ctx.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, "Bearer " + tokens.current())). The tokens object caches the access token and refreshes it shortly before it expires, so calls do not fetch a new token each time and the find method no longer needs a token parameter.

What exception do timeouts produce?

Connection and read timeouts surface as a ProcessingException, usually wrapping a SocketTimeoutException or similar from the connector. They are not WebApplicationExceptions, because no HTTP response was received, so callers should handle them separately, for example with a retry or a circuit breaker.

Does the default connector pool connections?

It depends on the implementation and the connector configured. Jersey's default connector relies on the JDK's HTTP keep-alive, while connectors based on Apache HttpClient or similar have explicit pools with per-host limits. Closing responses matters with all of them, and we should check the connector's pool size settings for our load.

6Conclusion

In this answer, we wrote an InventoryClient that builds one Client with connect and read timeouts, resolves the sku template, sends the bearer token, maps 404 to Optional.empty() and reads the Item on success. We saw why every Response must be closed, preferably with try-with-resources, because unread responses keep connections out of the pool and exhaust it under load, and we compared the typed get(Item.class) style, which throws NotFoundException for 404, and a ClientRequestFilter that adds the token to every request.

What to say in the interviewAbout 100 seconds aloud

Open with

I would create one Client per remote service, at startup, with ClientBuilder.newBuilder(), a connect timeout of a couple of seconds and a read timeout of a few seconds, and reuse it, because a Client holds the connection pool and providers, is expensive to create and is safe to share.

Then, if they want more

From it I keep a WebTarget for the base URL with path items/{sku}. For each call I resolve the template with resolveTemplate("sku", sku), which also encodes the value, call request with application/json, add the Authorization header with Bearer and the token, and call get(). I put the Response in a try-with-resources block. If the status is 404, I return Optional.empty().

If it is another non-success status, I throw an exception. Otherwise I return Optional.of(r.readEntity(Item.class)). The resources to close are the Response, on every path, and the Client when the application shuts down. The Response matters most: a connection is leased for each request and only goes back to the pool when the body is consumed or the response is closed.

In the 404 branch we never read the body, so without closing, each 404 leaks a connection, and under load the pool runs out and every call starts timing out. An alternative style is get(Item.class), which reads and closes automatically and throws NotFoundException for 404, which I would catch and turn into an empty Optional.

To avoid repeating the token, I would register a ClientRequestFilter that adds it to every request.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Jakarta EE specifications
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Using the JAX-RS client API, write code that calls GET https://inventory/api/items/{sku}...": https://scrivio-interview-library.netlify.app/java/jax-rs/420459b79f/