Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write an HTTP interface client for GET /products/{id} and POST /products, and show how to create the proxy backed by RestClient.

We declare a Java interface annotated with @HttpExchange("/products"), add a method with @GetExchange("/{id}") that takes a @PathVariable id and returns Product, and a method with @PostExchange that takes a @RequestBody Product. Then we build an HttpServiceProxyFactory from RestClientAdapter.create(restClient) and call createClient(ProductClient.class), which gives us a proxy that turns each method call into an HTTP request. Spring Framework 7 and Spring Boot 4 add @ImportHttpServices and auto-configuration to register groups of such clients without the factory code.

Why this question is asked

Writing the same RestClient call chain for every endpoint of a dependency gets repetitive, and the URLs, path variables and types end up scattered across the code. HTTP interface clients let us describe the remote API once, as a Java interface, and let Spring generate the implementation, much like Spring Data does for repositories. Interviewers ask for this in code because it is now the recommended way to write declarative clients in Spring, and the details (where the base URL goes, which adapter to use, how errors surface) show whether we have used it for real. In this answer, we will write the interface, create the proxy backed by RestClient, call it, look at the return types it supports, see how errors surface, and finish with the newer registration support in Spring Framework 7.

1A Quick Recap of HTTP Interface Clients

An HTTP interface client is a plain Java interface whose methods carry annotations describing HTTP requests. We never write a class that implements it. At startup, Spring creates a proxy, an object generated at runtime that implements the interface. When we call a method on the proxy, it reads the annotations, builds the request (method, URL, headers, body), hands it to an underlying client such as RestClient, and converts the response back into the method's return type.

The feature has been part of Spring Framework since version 6.0, so it needs no Spring Cloud dependency. The annotations live in org.springframework.web.service.annotation, and the method parameters reuse familiar ones from Spring MVC, such as @PathVariable, @RequestParam, @RequestHeader and @RequestBody.

2Declaring the Interface

Here is a client for GET /products/{id} and POST /products. The type-level @HttpExchange holds the common path, and each method adds its own part.

Java
public record Product(Long id, String name, BigDecimal price) {}
@HttpExchange("/products")
public interface ProductClient {
@GetExchange("/{id}")
Product get(@PathVariable("id") long id); // GET /products/42
@PostExchange
Product create(@RequestBody Product product); // POST /products, JSON body
}

Notice that the paths combine: "/products" from the interface and "/{id}" from the method give /products/{id}. We name the path variable explicitly as @PathVariable("id"). Without the name, Spring has to read parameter names from the compiled class, which only works when the code is compiled with the -parameters flag. Spring Boot's Maven and Gradle plugins set that flag, but naming it explicitly keeps the client working in any build.

The request body is written with the same message converters RestClient uses, so with Jackson on the classpath the Product record is sent as JSON, and the JSON response is read back into a Product.

3Creating the Proxy Backed by RestClient

The interface needs something to execute the requests. We build a RestClient with the base URL and any defaults, wrap it in a RestClientAdapter, and ask an HttpServiceProxyFactory to create the client.

Java
@Configuration
class ProductClientConfig {
@Bean
ProductClient productClient(RestClient.Builder builder) {
RestClient restClient = builder
.baseUrl("https://catalog.example.com")
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.build();
RestClientAdapter adapter = RestClientAdapter.create(restClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
return factory.createClient(ProductClient.class);
}
}
// Using it from any bean:
Product p = productClient.get(42); // GET https://catalog.example.com/products/42
Product saved = productClient.create(new Product(null, "Lamp", new BigDecimal("39.90")));
System.out.println(saved.id()); // 1017, the id the server assigned
Step throughWhat happens when we call productClient.get(42)
Our serviceProductClient proxyRestClientCatalog API
get(42)
read @GetExchange, build GET /products/42
execute request
GET /products/42
200 OK, JSON body
Product, via message converters
Product

7 messages in order. Play them, or step through them one at a time.

Notice that we inject Spring Boot's RestClient.Builder instead of calling RestClient.builder() ourselves. The Boot builder already carries the configured message converters and Micrometer observation, so every call through the interface is recorded as an http.client.requests metric and traced. Timeouts, interceptors and status handlers are all configured on the RestClient, and the interface inherits them.

The factory is cheap to create and the proxy is thread-safe, so we create each client once, as a singleton bean, and inject it wherever it is needed.

4Return Types the Methods Can Use

The return type tells the proxy how much of the response we want. With a RestClientAdapter we can return the body type itself, such as Product, or void when we do not care about the body. We can return ResponseEntity<Product> when we also need the status and headers, for example a Location header after a POST, or HttpHeaders alone for a HEAD-style call.

If we build the factory from a WebClientAdapter instead, the methods can also return reactive types such as Mono<Product> or Flux<Product>, and the calls become non-blocking. The interface is the same idea in both worlds; the adapter decides the execution model.

Java
@PostExchange
ResponseEntity<Product> createWithHeaders(@RequestBody Product product);
// response.getStatusCode() -> 201 CREATED
// response.getHeaders().getLocation() -> https://catalog.example.com/products/1017
// With WebClientAdapter.create(webClient):
@GetExchange("/{id}")
Mono<Product> getAsync(@PathVariable("id") long id);

5Registering Groups of Clients in Spring Framework 7

Writing a configuration method per client gets repetitive when a service talks to many APIs. Spring Framework 7 adds an HTTP service registry with an @ImportHttpServices annotation that registers interfaces as beans in named groups, each group sharing one configured RestClient. Spring Boot 4 auto-configures those groups and lets us set properties such as the base URL per group in application properties. The exact annotation attributes and property names are new, so check your version before using them.

Java
@Configuration
@ImportHttpServices(group = "catalog", types = { ProductClient.class, CategoryClient.class })
class HttpClientsConfig {}
// application.properties (Spring Boot 4; check the property names for your version)
// spring.http.serviceclient.catalog.base-url=https://catalog.example.com

With this in place, ProductClient is simply injected; Spring builds the proxy, the adapter and the RestClient for the group.

6Follow-up questions

How do errors surface from an HTTP interface method?

Through the underlying client. With RestClient, a 4xx response throws HttpClientErrorException and a 5xx throws HttpServerErrorException, both subclasses of RestClientResponseException, and specific statuses have subclasses such as HttpClientErrorException.NotFound. Network problems such as a refused connection or a read timeout throw ResourceAccessException. To change this, we register defaultStatusHandler on the RestClient builder, for example to turn 404 into our own ProductNotFoundException, and every method of the interface gets that behaviour. With a WebClientAdapter, the Mono fails with WebClientResponseException instead.

How do you pass query parameters and headers?

With the same annotations as Spring MVC. A parameter annotated @RequestParam("page") int page becomes ?page=2, and @RequestHeader("X-Tenant") String tenant becomes a header. A parameter of type URI overrides the base URL for that call, which is useful when a server returns a link to follow.

How would you test a client like this?

I would start a stub server such as WireMock or MockWebServer, point the RestClient's base URL at it, and assert both directions: that get(42) sends GET /products/42 with the expected headers, and that a canned JSON response becomes the right Product. I would also test the 404 and 500 cases, because error mapping is where clients most often differ from expectations.

7Conclusion

In this answer, we wrote an HTTP interface client by declaring ProductClient with @HttpExchange("/products"), a @GetExchange("/{id}") method with a named @PathVariable, and a @PostExchange method with a @RequestBody. We created the proxy with HttpServiceProxyFactory.builderFor(RestClientAdapter.create(restClient)).build().createClient(ProductClient.class), and saw that timeouts, interceptors, metrics and error handling all come from the RestClient behind it. Methods can return bodies, ResponseEntity or, with a WebClientAdapter, reactive types, and Spring Framework 7 with Spring Boot 4 can register whole groups of clients for us.

What to say in the interviewAbout 80 seconds aloud

Open with

I would declare an interface, ProductClient, annotated with @HttpExchange("/products"). It has a method annotated @GetExchange("/{id}") returning Product with a parameter @PathVariable("id") long id, and a method annotated @PostExchange returning Product that takes the product as @RequestBody.

Then, if they want more

I name the path variable explicitly so it does not depend on the -parameters compiler flag. To create it, I build a RestClient from the Boot RestClient.Builder with the base URL, so it gets the message converters and Micrometer observation, wrap it with RestClientAdapter.create, build an HttpServiceProxyFactory with builderFor(adapter).build(), and call createClient(ProductClient.class). I expose that as a singleton bean.

At runtime the proxy reads the annotations, builds GET /products/42 or a POST with a JSON body, and lets RestClient execute it and convert the response. Methods can return the body, void, or ResponseEntity if I need headers like Location, and with a WebClientAdapter they can return Mono or Flux.

Errors come from RestClient, so a 404 throws HttpClientErrorException.NotFound unless I register a default status handler to map it to my own exception. And in Spring Framework 7 with Boot 4 there is @ImportHttpServices to register groups of these clients with configuration properties, so I would check which version the project is on.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 4, Spring Framework 7
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.
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 "Write an HTTP interface client for GET /products/{id} and POST /products, and show how...": https://scrivio-interview-library.netlify.app/spring-boot/http-clients/939da8b02a/