Sub topic 2
Describing endpoints with @HttpExchange
This chapter covers how to describe a remote HTTP endpoint as a Java interface method. It assumes you know Java 17 records and interfaces, basic Spring beans and dependency injection, HTTP methods and status codes, and Spring MVC annotations such as @PathVariable and @RequestParam. Building the proxy that implements the interface, and registering it as a bean, come in later chapters. Here the focus is the annotations themselves.
The annotation family
An HTTP interface is a plain Java interface. Each method stands for one HTTP request. You describe the request with annotations, and Spring generates the implementation at runtime.
The annotations live in org.springframework.web.service.annotation:
| Annotation | HTTP method |
|---|---|
| `@HttpExchange` | Any method, set through the `method` attribute |
| `@GetExchange` | GET |
| `@PostExchange` | POST |
| `@PutExchange` | PUT |
| `@PatchExchange` | PATCH |
| `@DeleteExchange` | DELETE |
@HttpExchange is the general annotation. The other five are shortcuts that fix the HTTP method for you. They are meta-annotated with @HttpExchange, so they carry the same attributes. In day-to-day code you use the shortcuts on methods and keep @HttpExchange for the type level.
This is the interface used throughout this tutorial:
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.service.annotation.PostExchange;
@HttpExchange("/todos")
public interface TodoClient {
@GetExchange("/{id}")
Todo getTodo(@PathVariable long id);
@GetExchange
List<Todo> listByUser(@RequestParam long userId);
@PostExchange
ResponseEntity<Todo> create(@RequestBody Todo todo);
}
record Todo(Long id, Long userId, String title, boolean completed) {}The three methods map to these requests:
| Method call | Request |
|---|---|
| `getTodo(1)` | `GET /todos/1` |
| `listByUser(7)` | `GET /todos?userId=7` |
| `create(todo)` | `POST /todos` with a JSON body |
Notice that the argument annotations come from Spring MVC (org.springframework.web.bind.annotation). The same annotation names that describe what a server accepts are reused to describe what a client sends. Argument binding is the topic of the next chapter, so this chapter only uses the simple cases.
How the type-level path combines with method paths
When @HttpExchange sits on the interface, its url attribute (also available as value) becomes a prefix for every method. The method's own path is appended to it.
@HttpExchange("/todos")plus@GetExchange("/{id}")gives/todos/{id}.@HttpExchange("/todos")plus a bare@GetExchangegives/todos.
A bare method annotation is valid. It means "use the type-level path with this HTTP method". That is how listByUser and create above both target /todos.
The combined path is then resolved against the base URL configured on the RestClient. If the client has base URL https://jsonplaceholder.typicode.com, then getTodo(1) calls https://jsonplaceholder.typicode.com/todos/1. Configuring the base URL is covered in a later chapter.
The type-level annotation can also set the other attributes, and they apply to every method as defaults. You will see which ones next.
Attributes of @HttpExchange
All the exchange annotations share these attributes.
| Attribute | Purpose |
|---|---|
| `url` (alias `value`) | The request path or full URL, possibly with `{placeholders}` |
| `method` | The HTTP method. Only needed on plain `@HttpExchange` |
| `contentType` | The `Content-Type` of the request body, such as `application/json` |
| `accept` | An array of media types for the `Accept` header |
| `headers` | Fixed headers in `"Name=value"` form (available from Spring Framework 6.2) |
| `params` | Fixed query parameters in `"name=value"` form (available from Spring Framework 6.2) |
A type-level @HttpExchange can set contentType and accept once for the whole interface:
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.service.annotation.PostExchange;
@HttpExchange(url = "/todos", accept = "application/json", contentType = "application/json")
public interface JsonTodoClient {
@GetExchange("/{id}")
String raw(@org.springframework.web.bind.annotation.PathVariable long id);
@PostExchange
void send(@org.springframework.web.bind.annotation.RequestBody String json);
}A method-level attribute overrides the type-level value for that method. For contentType and accept, the method value replaces the type value. The url is the exception, because the two paths are concatenated.
Fixed headers and parameters
If a header or parameter has the same value on every call, you do not need a method argument for it. Put it in the annotation:
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
@HttpExchange("/todos")
public interface VersionedTodoClient {
@GetExchange(url = "/{id}", headers = "X-Api-Version=2")
Todo getTodo(@org.springframework.web.bind.annotation.PathVariable long id);
@GetExchange(params = "completed=true")
java.util.List<Todo> listCompleted();
}listCompleted() always sends GET /todos?completed=true. Arguments that vary per call belong in method parameters, not in these attributes.
URL templates and placeholders
The url can contain URI template variables in braces, such as {id}. The variable is filled from a method argument. By default, an argument annotated with @PathVariable fills the variable with the matching name. If the Java parameter name and the placeholder differ, name the variable explicitly:
@GetExchange("/{id}")
Todo getTodo(@PathVariable("id") long todoId);Without an explicit name, Spring matches by parameter name. That requires the code to be compiled with the -parameters flag. Spring Boot's Maven and Gradle plugins turn this flag on by default, so it normally works. If you compile some other way, the symptom is an error about a missing name for the argument. Adding the name to the annotation removes the dependency on the compiler flag.
Two other points about the URL:
- Encoding. Template variable values are URI-encoded when they are expanded. Pass
"hello world"as a path variable and it is sent ashello%20world. Do not encode the value yourself, or it will be encoded twice. - Dynamic URLs. If a method takes a
java.net.URIargument as its first parameter, that URI replaces the annotation's URL entirely, and the base URL is ignored. This is useful when the server returns links such as pagination URLs that you want to follow.
import java.net.URI;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
@HttpExchange
public interface LinkFollower {
@GetExchange
String fetch(URI uri);
}The call path at a glance
When you call an interface method, a proxy reads the annotations, builds a request, and runs it through the underlying client. The diagram shows the flow for getTodo(1).
The annotation reading happens once, when the proxy is created, not on every call. A mistake in the annotations, such as two body arguments, therefore fails at startup rather than at the first request. This is a benefit of the declarative style, because the failure happens early and with a clear message.
Where to place the annotations
You can put @HttpExchange on the interface, on methods, or both. These are the combinations you will meet:
- Type-level
@HttpExchangeplus method-level shortcuts. The most common pattern, used above. The type holds the shared path and defaults. The methods hold the HTTP method and the rest of the path. - Method-level annotations only. Useful when the endpoints do not share a prefix. Each method then carries its full path.
- Plain
@HttpExchange(method = "GET", url = "/x")on a method. Equivalent to@GetExchange("/x"). You would use it only for an HTTP method that has no shortcut, such as HEAD or OPTIONS.
Every method that you want Spring to implement must carry some exchange annotation. A method without one is not treated as an endpoint. The proxy factory rejects it when it creates the proxy, unless the method is a default method on the interface, which Spring leaves alone.
Default methods
A default method is useful to add convenience on top of the declared endpoints. It runs as ordinary Java and may call the other interface methods:
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
@HttpExchange("/todos")
public interface TodoClientWithHelpers {
@GetExchange("/{id}")
Todo getTodo(@PathVariable long id);
@GetExchange
List<Todo> listByUser(@RequestParam long userId);
default List<Todo> openTodosFor(long userId) {
return listByUser(userId).stream()
.filter(todo -> !todo.completed())
.toList();
}
}openTodosFor is not an HTTP call. It is Java code that makes one call, so there is nothing to annotate.
Common errors
- Forgetting the leading slash.
@GetExchange("todos")is resolved differently from@GetExchange("/todos")once a base URL with a path is involved. Start paths with/and keep the base URL free of a trailing slash. - Using the wrong annotations.
@GetMappingand@PostMappingare server-side annotations and are ignored here. A method annotated with them is not an endpoint. Use the*Exchangeannotations. - Missing parameter names. An error about argument names usually means the
-parameterscompiler flag is missing. Name the path variables and request parameters explicitly. - Mismatched placeholder. A
{id}in the URL with no matching argument leaves the template unresolved, and the call fails when the URI is expanded. Check that every placeholder has an argument. - Duplicated type-level and method-level paths. Because the two paths are joined, repeating
/todoson both produces/todos/todos.
Summary
- Each method of an
@HttpExchangeinterface describes one HTTP request. @GetExchange,@PostExchange,@PutExchange,@PatchExchange, and@DeleteExchangefix the HTTP method. Plain@HttpExchangetakes it from themethodattribute.- A type-level path is a prefix for the method paths. A method-level
contentTypeoracceptoverrides the type-level value. {placeholders}in the URL are filled from arguments and are URI-encoded. AURIfirst argument replaces the URL.defaultmethods hold ordinary Java logic over the declared endpoints.
Exercise
An interface is annotated @HttpExchange("/orders"). It has the method @GetExchange("/{orderId}/items") List<Item> items(@PathVariable long orderId);. The RestClient has base URL https://shop.example.com. Which URL does items(42) call, and what changes if you also write @GetExchange("/orders/{orderId}/items") on the method?
Show answer
It calls GET https://shop.example.com/orders/42/items. The type-level /orders is prefixed to the method path /{orderId}/items. If the method path also began with /orders, the two would be joined into /orders/orders/{orderId}/items, so the request would go to https://shop.example.com/orders/orders/42/items and probably return 404.
Exercise
You need an interface method that sends HEAD /todos/{id} and an interface method that always sends the header X-Api-Version: 2. Which annotation and attributes do you use for each?
Show answer
HEAD has no shortcut annotation, so use @HttpExchange(method = "HEAD", url = "/todos/{id}") on the method. For the fixed header, set headers = "X-Api-Version=2" on the exchange annotation. Per-call values should be method arguments instead.
Exercise
A teammate writes @GetMapping("/todos/{id}") Todo getTodo(@PathVariable long id); on a client interface and says the proxy fails when it is created. Why, and what is the fix?
Show answer
@GetMapping is a Spring MVC server annotation. The proxy factory only recognizes the exchange annotations, so the method has no endpoint description. Replace it with @GetExchange("/todos/{id}"), or put @HttpExchange("/todos") on the type and use @GetExchange("/{id}").