Sub topic 4
Building Request URIs
Every RestClient call starts by describing where the request goes. This chapter covers the uri(...) methods, URI templates, query parameters, base URLs, and the encoding rules that decide what ends up on the wire. It assumes you can already create a RestClient with a base URL (previous chapter) and are comfortable with HTTP query strings and percent-encoding.
The uri(...) overloads
The uri step is the first call after choosing the HTTP method. It accepts several argument shapes.
| Overload | Use it when |
|---|---|
| `uri(String template, Object... variables)` | The URI has a few variables and positional order is obvious. |
| `uri(String template, Map<String, ?> variables)` | You prefer named variables, or the same variable appears twice. |
| `uri(Function<UriBuilder, URI> fn)` | You need to build paths and query parameters programmatically. |
| `uri(String template, Function<UriBuilder, URI> fn)` | You want a template as the starting point, then add more with a builder. |
| `uri(URI uri)` | You already have a finished `java.net.URI`. |
The first four go through the client's UriBuilderFactory, which applies the base URL and the encoding rules. uri(URI) skips all of that. The URI is sent as is, so the base URL is not prepended.
Templates and variables
A URI template contains placeholders in curly braces. RestClient replaces each placeholder with a value you supply, and encodes the value for you.
Todo todo = restClient.get()
.uri("/todos/{id}", 42)
.retrieve()
.body(Todo.class);With several variables, positional values fill the placeholders in order of appearance. A map names them instead:
Todo todo = restClient.get()
.uri("/users/{userId}/todos/{id}", Map.of("userId", 7, "id", 3))
.retrieve()
.body(Todo.class);Use a map when readability matters or when a placeholder repeats. With positional values, each placeholder is a separate slot, so a repeated name needs its value passed twice. A map supplies it once.
Seeing what a template produces
You can check the result without sending any request by using the DefaultUriBuilderFactory that RestClient uses internally. The next program needs only spring-web on the classpath.
import java.net.URI;
import java.util.Map;
import org.springframework.web.util.DefaultUriBuilderFactory;
public class UriDemo {
public static void main(String[] args) {
DefaultUriBuilderFactory factory =
new DefaultUriBuilderFactory("https://api.example.com/v1");
URI byId = factory.expand("/todos/{id}", 42);
URI search = factory.expand("/search/{term}", "a b/c");
URI title = factory.expand("/todos?title={title}", "fish & chips");
URI named = factory.expand("/users/{userId}/todos/{id}",
Map.of("userId", 7, "id", 3));
URI built = factory.builder()
.path("/todos")
.queryParam("completed", true)
.queryParam("userId", "{userId}")
.queryParam("tag", "java", "spring")
.build(7);
System.out.println(byId);
System.out.println(search);
System.out.println(title);
System.out.println(named);
System.out.println(built);
}
}The program prints:
https://api.example.com/v1/todos/42
https://api.example.com/v1/search/a%20b%2Fc
https://api.example.com/v1/todos?title=fish%20%26%20chips
https://api.example.com/v1/users/7/todos/3
https://api.example.com/v1/todos?completed=true&userId=7&tag=java&tag=springThree things to notice:
- The base path
/v1is kept and the template path is appended to it. - The
/insidea b/cbecame%2F. A variable value is always one path segment or one query value, never extra structure. - The
&infish & chipsbecame%26, so the value cannot be mistaken for a parameter separator.
How a uri call is resolved
The following diagram shows the steps from your arguments to the final URI.
Query parameters with UriBuilder
You can write a query string in the template:
restClient.get().uri("/todos?completed={done}&userId={user}", false, 7)This works for fixed shapes. When parameters are optional or repeated, use the UriBuilder function form. The builder you receive already starts from the client's base URL.
import java.util.List;
import java.util.Optional;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.web.client.RestClient;
record Todo(long id, String title, boolean completed) {}
class TodoSearch {
private final RestClient restClient;
TodoSearch(RestClient restClient) {
this.restClient = restClient;
}
List<Todo> search(boolean completed, long userId, String titleOrNull) {
return restClient.get()
.uri(uriBuilder -> uriBuilder
.path("/todos")
.queryParam("completed", completed)
.queryParam("userId", "{userId}")
.queryParamIfPresent("title", Optional.ofNullable(titleOrNull))
.build(userId))
.retrieve()
.body(new ParameterizedTypeReference<List<Todo>>() {});
}
List<Todo> page(long userId, int page) {
return restClient.get()
.uri("/users/{userId}/todos", uriBuilder -> uriBuilder
.queryParam("page", "{page}")
.build(Map.of("userId", userId, "page", page)))
.retrieve()
.body(new ParameterizedTypeReference<List<Todo>>() {});
}
}Add import java.util.Map; for the second method. The key points:
queryParam("completed", completed)takes a literal value. It is encoded when the URI is built.queryParam("userId", "{userId}")takes a placeholder, filled by the arguments tobuild(...). Prefer this form when the value comes from user input.queryParamIfPresentadds the parameter only when theOptionalhas a value, which avoidstitle=nullappearing in a URL.queryParam("tag", "java", "spring")orqueryParam("tag", List.of("java", "spring"))produces a repeated parameter,tag=java&tag=spring.build(...)accepts either positional values or aMap, just like the template overloads.
Base URLs and default variables
RestClient.Builder.baseUrl(...) sets a prefix for every request that uses a template or builder function. The base can include a path such as /v1, and it can itself contain placeholders. You then fill them once with defaultUriVariables:
RestClient client = RestClient.builder()
.baseUrl("https://{host}/v1")
.defaultUriVariables(Map.of("host", "api.example.com"))
.build();This is useful when the host differs per environment but you want one client definition. A variable passed in an individual uri(...) call overrides a default variable of the same name.
How encoding works
The DefaultUriBuilderFactory has an encoding mode. RestClient uses TEMPLATE_AND_VALUES unless you change it.
| Mode | Behavior |
|---|---|
| `TEMPLATE_AND_VALUES` | Encodes the literal template text first, then strictly encodes each variable value. This is the default. |
| `VALUES_ONLY` | Leaves the template as written and strictly encodes values before expansion. |
| `URI_COMPONENT` | Expands first, then encodes only characters illegal in each URI component. Characters such as `/` and `&` in a value pass through. |
| `NONE` | Performs no encoding. |
"Strict" encoding means that every character outside the unreserved set (letters, digits, -, ., _, ~) is percent-encoded. That is why /, &, +, and ? inside a variable value are all escaped. This is the safest behavior for values that come from users, because a value cannot change the structure of the URL.
To change the mode, supply your own factory. Doing so replaces baseUrl and defaultUriVariables, so set the base on the factory too:
import org.springframework.web.client.RestClient;
import org.springframework.web.util.DefaultUriBuilderFactory;
import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode;
RestClient valuesOnlyClient() {
DefaultUriBuilderFactory factory =
new DefaultUriBuilderFactory("https://api.example.com");
factory.setEncodingMode(EncodingMode.VALUES_ONLY);
return RestClient.builder()
.uriBuilderFactory(factory)
.build();
}Common errors
Concatenating values into the template. This code looks harmless:
restClient.get().uri("/search?q=" + term)If term is a&admin=true, the server receives two parameters. If term contains {, the template parser may treat it as a placeholder and fail with an IllegalArgumentException. Pass the value as a variable instead: uri("/search?q={q}", term).
Double encoding. Variable values should be raw. If you pass "a%20b", strict encoding turns the % into %25 and the server sees a%2520b. Decode the value first, or pass an already-built URI through uri(URI).
Expecting the base URL to apply to a URI object. uri(URI.create("/todos/1")) has no host, and the request fails. A URI argument must be absolute because RestClient does not add the base to it.
Wrong number of variables. A template with two placeholders and one value throws IllegalArgumentException at the time of the call, not when the response arrives. This is the quickest error to diagnose, because it happens before any network traffic.
Braces in literal text. Query values such as JSON fragments contain { and }. Pass them as variables ("/items?filter={f}" with the JSON as the value) so the braces are treated as data.
Slash handling. A base of https://api.example.com/v1 plus a template of /todos gives /v1/todos. A template without the leading slash also works, because the factory joins the path segments. Pick one style and use it consistently across the codebase.
Testing URI construction
The DefaultUriBuilderFactory demo above is a valid unit test target. It needs no server and no Spring context. Assert on the URI string for the edge cases that matter in your project, such as spaces, slashes, and repeated parameters. A later chapter shows how MockRestServiceServer can assert on the request URI of a full RestClient call.
Exercise
A client is built with baseUrl("https://api.example.com/v1"). What URI does uri("/files/{name}", "reports/2026 q1.pdf") produce under the default encoding mode, and why is the slash in the name encoded?
Show answer
It produces https://api.example.com/v1/files/reports%2F2026%20q1.pdf. The default mode, TEMPLATE_AND_VALUES, strictly encodes variable values. The / in the value becomes %2F so the value stays inside one path segment, and the space becomes %20. The base path /v1 is kept and the template path is appended.
Exercise
Write a method List<Todo> byTags(List<String> tags) that calls GET /todos and sends each tag as a repeated tag query parameter, for example ?tag=java&tag=spring. What does the URI look like if the list is empty?
Show answer
Use the builder form: restClient.get().uri(b -> b.path("/todos").queryParam("tag", tags).build()).retrieve().body(new ParameterizedTypeReference<List<Todo>>() {}). For List.of("java", "spring") this yields /todos?tag=java&tag=spring. For an empty list, queryParam(String, Collection) adds no value, so the URI is just /todos. Check how the server treats a missing filter, because it may return every todo.
Exercise
A teammate writes restClient.get().uri("/search?q=" + userInput). Name two things that can go wrong and give the fix.
Show answer
First, characters such as &, #, or + in userInput change the structure or meaning of the query string, so the user can inject extra parameters. Second, a { or } in the input is parsed as a template placeholder and can cause an IllegalArgumentException. The fix is uri("/search?q={q}", userInput), which encodes the value strictly and treats it as data.