Sub topic 3
Binding arguments: path, query, headers, and body
This chapter assumes you know Spring MVC's @PathVariable, @RequestParam, @RequestHeader and @RequestBody. It also assumes you have read how @HttpExchange and its method-level variants describe an endpoint. Here you learn how each Java method argument becomes part of the outgoing HTTP request, and where binding fails.
The same annotations, the opposite direction
In a controller, these annotations read values out of an incoming request. On an HTTP interface they do the reverse. Each annotated argument writes a value into the outgoing request. The annotation classes are the same ones from org.springframework.web.bind.annotation, so the names are familiar. The direction is the only change.
The proxy that Spring generates inspects each argument when you call the method. It builds a request description from the URL template, the HTTP method and those argument values. It then hands the description to the underlying client, such as RestClient.
Supported arguments
The common argument types are in the table below.
| Argument | Effect on the request |
|---|---|
| `@PathVariable` | Fills a `{placeholder}` in the URL template |
| `@RequestParam` | Adds a query parameter, or a form field for form content types |
| `@RequestHeader` | Adds one header, or many when the argument is a `Map` |
| `@RequestBody` | Serializes the object as the request body |
| `@CookieValue` | Adds a cookie |
| `@RequestPart` | Adds one part of a multipart request |
| `URI` | Replaces the URL from the annotations |
| `HttpMethod` | Replaces the HTTP method from the annotation |
This chapter covers the first four in detail, plus URI, because those cover most real APIs.
A client that uses each binding
The interface below extends the TodoClient from earlier. It shows each binding once.
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
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("id") long id);
@GetExchange
List<Todo> search(
@RequestParam("userId") long userId,
@RequestParam(name = "completed", required = false) Boolean completed,
@RequestHeader("X-Request-Id") String requestId);
@GetExchange
List<Todo> findAll(
@RequestParam("id") List<Long> ids,
@RequestHeader Map<String, String> extraHeaders);
@PostExchange
Todo create(@RequestBody Todo todo);
}
record Todo(Long id, Long userId, String title, boolean completed) {}The following sections explain what each method sends.
Path variables
getTodo(7) sends GET /todos/7. The type-level path /todos is prefixed to the method-level path /{id}. The proxy replaces the {id} placeholder with the argument value.
The proxy URL-encodes path values. A string such as a b/c is encoded as a single path segment rather than split into three segments by the slash. Non-string types, like the long above, are converted to strings through a conversion service. The proxy factory uses a default one unless you configure your own.
A placeholder with no matching argument is a mistake. The request is built with the placeholder still unresolved, and it fails at runtime, not at startup. Keep placeholder names and argument names in sync.
Query parameters
search(1, true, "abc") sends GET /todos?userId=1&completed=true. Every @RequestParam becomes a query parameter. The same rules apply as in Spring MVC:
requireddefaults totrue. Passingnullfor a required parameter throws anIllegalArgumentExceptionbefore any request is sent.- Setting
required = falsemakes anullargument disappear from the URL.search(1, null, "abc")sendsGET /todos?userId=1. Optional<T>arguments are also accepted and omitted when empty.- A
defaultValuefills in when the argument isnull.
A collection produces repeated parameters. findAll(List.of(1L, 2L), Map.of()) sends GET /todos?id=1&id=2. A Map<String, String> argument annotated with @RequestParam adds one parameter per entry, which suits APIs with many optional filters.
The proxy encodes query values for you. Do not pre-encode a value, or it is encoded twice.
Form submissions
@RequestParam behaves differently when the request content type is application/x-www-form-urlencoded. The values then go into the request body as form fields, not the URL.
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.service.annotation.PostExchange;
@HttpExchange("/auth")
public interface AuthClient {
@PostExchange(url = "/login", contentType = "application/x-www-form-urlencoded")
void login(@RequestParam("username") String username,
@RequestParam("password") String password);
}The contentType attribute on the exchange annotation is what triggers this behavior. Without it, the same method would put the credentials in the URL, where proxies and access logs record them.
Headers
@RequestHeader("X-Request-Id") String requestId adds one header whose value is the argument. A few details matter:
- A header with a
nullvalue andrequired = falseis omitted, as with query parameters. - A
Map<String, String>argument adds one header per entry. This suits callers that decide the headers at run time. - Use headers that change per call as arguments. Headers that every call needs, such as an API key, belong in the client's defaults, which a later chapter covers.
The @GetExchange, @PostExchange and related annotations also have contentType and accept attributes. Use those for the standard Content-Type and Accept headers. A fixed value belongs in the annotation. An argument is for values that vary.
Request bodies
create(new Todo(null, 1L, "write docs", false)) sends a POST /todos request whose body is the serialized record. The RestClient message converters choose the format. With JSON on the classpath, which Spring Boot starters provide, the body is JSON and the Content-Type header is set to match.
Only one argument can be the body. If you need to send several values, wrap them in one object. If the endpoint expects a multipart upload, use @RequestPart for each part.
Pass null for a @RequestBody argument only if you declare required = false. Otherwise the call fails before sending.
Overriding the URL with URI
Sometimes the full URL comes from data you received earlier, such as a next link in a paginated response. Declare a URI argument.
import java.net.URI;
import java.util.List;
import org.springframework.web.service.annotation.GetExchange;
public interface PageClient {
@GetExchange
List<Todo> fetchPage(URI uri);
}The value of the URI argument replaces the URL that the annotations would have built. A base URL set on the RestClient is ignored for that call. Path variables and query parameters on the same method then have nothing to fill, so avoid mixing them with a URI argument.
Checking the binding in a test
You can check what a method sends without a server. MockRestServiceServer records the request and matches it against your expectations.
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
class TodoClientBindingTest {
@Test
void omitsNullOptionalParamAndSendsHeader() {
RestClient.Builder builder = RestClient.builder().baseUrl("http://localhost");
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
server.expect(requestTo("http://localhost/todos?userId=1"))
.andExpect(header("X-Request-Id", "abc"))
.andRespond(withSuccess("[]", MediaType.APPLICATION_JSON));
TodoClient client = HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(builder.build()))
.build()
.createClient(TodoClient.class);
client.search(1L, null, "abc");
server.verify();
}
}If the URL or the header differs, verify() or the call itself fails with a message showing what was sent. Testing is covered fully in a later chapter.
Common errors
| Symptom | Likely cause |
|---|---|
| Error about a missing or unnamed argument | Parameter names are not in the compiled class. Add `-parameters` or name each annotation |
| `IllegalArgumentException` before any request | A `null` passed for a required parameter or body |
| Literal `{id}` or a 404 for a path with braces | The placeholder name does not match the `@PathVariable` name |
| Credentials appear in URLs | Form content type was not set, so `@RequestParam` went to the query string |
| Characters like `%2B` appear doubled | A value was encoded by hand and then encoded again by the proxy |
| Unsupported argument type error | An argument has no annotation and is not a type the proxy recognizes |
The last row matters because an unannotated argument is not treated as a body by default. Annotate each argument explicitly.
Exercise
A method is declared as @PostExchange(url = "/search", contentType = "application/x-www-form-urlencoded") List<Todo> search(@RequestParam("q") String q). A second method is the same but has no contentType. Where does q go in each case?
Show answer
With the form content type, q is sent as a form field in the request body. Without it, q is added to the URL as a query parameter, as in /search?q=....
Exercise
You call search(5L, null, "req-1") on the TodoClient shown earlier, where completed is declared with required = false. What URL is requested, and which header is sent?
Show answer
The URL is /todos?userId=5, with the base URL in front. The null completed parameter is omitted. The header X-Request-Id: req-1 is sent.