Sub topic 4
Building request URIs
This chapter assumes you can create a RestClient with a base URL, as shown in the previous chapter. You should also know basic HTTP: path segments, query strings, and percent-encoding. The goal is to build request URIs safely, without concatenating strings by hand.
Why not concatenate strings
A URI built with + is easy to get wrong. A value containing a space, &, / or ? changes the meaning of the URI unless you encode it. A RestClient gives you three ways to build URIs. All of them handle encoding for you.
| Approach | Use it when |
|---|---|
| URI template with variables | The path and query are mostly fixed and a few values change |
| `UriBuilder` function | You have optional or repeated query parameters |
| A ready-made `java.net.URI` | You already have a complete, encoded URI |
URI templates
A URI template is a string with placeholders in braces, such as /todos/{id}. You pass the values after the template. RestClient expands the placeholders in order and encodes each value.
import org.springframework.web.client.RestClient;
class TemplateExamples {
private final RestClient restClient;
TemplateExamples(RestClient restClient) {
this.restClient = restClient;
}
String byId(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.body(String.class);
}
String byUserAndStatus(long userId, boolean completed) {
return restClient.get()
.uri("/users/{userId}/todos?completed={completed}", userId, completed)
.retrieve()
.body(String.class);
}
}Variables are matched by position. In the second method, userId fills {userId} and completed fills {completed}.
If the base URL is https://api.example.com, the first call requests https://api.example.com/todos/42. The template path is appended to the base URL.
Using a map for named variables
Positional values become hard to read when there are many of them. Pass a Map instead, and each placeholder is looked up by name.
import java.util.Map;
import org.springframework.web.client.RestClient;
class MapExamples {
private final RestClient restClient;
MapExamples(RestClient restClient) {
this.restClient = restClient;
}
String search(long userId, String title) {
Map<String, Object> vars = Map.of("userId", userId, "title", title);
return restClient.get()
.uri("/users/{userId}/todos?title={title}", vars)
.retrieve()
.body(String.class);
}
}With title set to buy milk & eggs, the query value is encoded as a single value. The & does not start a new parameter.
Encoding behavior
Template variables are encoded strictly. Characters that have meaning in a URI are escaped inside the value. A / in a path variable becomes %2F, so the value stays inside one path segment.
String file(String name) {
// name = "reports/2026.csv" is sent as /files/reports%2F2026.csv
return restClient.get()
.uri("/files/{name}", name)
.retrieve()
.body(String.class);
}Do not encode a value yourself before passing it. The client would encode the % signs a second time, and the server would receive %252F instead of %2F.
The UriBuilder function
Templates are awkward when a query parameter is optional. The uri method also accepts a function that receives a UriBuilder. You add path segments and query parameters in code, so you can skip parameters that are absent.
import org.springframework.web.client.RestClient;
class BuilderExamples {
private final RestClient restClient;
BuilderExamples(RestClient restClient) {
this.restClient = restClient;
}
String list(Long userId, String title, int page) {
return restClient.get()
.uri(uriBuilder -> {
uriBuilder.path("/todos");
if (userId != null) {
uriBuilder.queryParam("userId", userId);
}
if (title != null) {
uriBuilder.queryParam("title", "{title}");
}
return uriBuilder
.queryParam("page", page)
.build(title);
})
.retrieve()
.body(String.class);
}
}The builder starts from the client's base URL, so you only add the path. Passing a value as a {title} placeholder and supplying it in build(...) makes the builder encode it. A call with userId null and title null requests /todos?page=2. Be careful with build(title) when title is null and no placeholder was added. The extra argument is ignored, which is safe. A placeholder with no matching argument throws an exception.
Complete URIs
If you already have a java.net.URI, pass it directly. The client uses it as given, and the base URL is not applied.
import java.net.URI;
String fromUri() {
URI uri = URI.create("https://api.example.com/todos/7");
return restClient.get()
.uri(uri)
.retrieve()
.body(String.class);
}This suits cases such as following a next link returned by a paginated API.
Common errors
- Pre-encoding a value and then passing it as a variable. This produces double encoding.
- Concatenating user input into the template string. Pass it as a variable instead.
- Supplying fewer variables than placeholders. The call fails with an
IllegalArgumentException. - Expecting the base URL to apply to a full
java.net.URI. It does not.
Exercise
A client has the base URL https://api.example.com. You call .uri("/files/{name}", "a/b.txt"). What URI is requested, and why?
Show answer
It requests https://api.example.com/files/a%2Fb.txt. Template variables are encoded strictly, so the / inside the value becomes %2F and the value stays in a single path segment.
Exercise
Write a uri call that sends GET /todos?page=3 and adds userId as a query parameter only when it is not null.
Show answer
Use the function form: .uri(b -> { b.path("/todos").queryParam("page", 3); if (userId != null) { b.queryParam("userId", userId); } return b.build(); }). The builder lets you add parameters conditionally, which a fixed template cannot do.