Quick revision
The short answer
We inject the RestClient.Builder that Spring Boot auto-configures, build a client with a baseUrl, and write restClient.get().uri("/users/{id}", id).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).retrieve().onStatus(status -> status.value() == 404, (req, res) -> { throw new NotFoundException(id); }).body(UserDto.class). We use toEntity(UserDto.class) instead of body() when we need the status or headers, and without onStatus a 4xx or 5xx would throw HttpClientErrorException or HttpServerErrorException.
What to remember
In this answer, we wrote a RestClient call that fetches GET /users/{id} into a UserDto. We built the client once from Spring Boot's auto-configured RestClient.Builder with a baseUrl, used a URI template, set the bearer token with the Authorization header, turned 404 into NotFoundException with onStatus, and decoded with body(UserDto.class) or toEntity() when status and headers matter. Without onStatus, 4xx and 5xx raise HttpClientErrorException or HttpServerErrorException, and a ParameterizedTypeReference reads generic types such as List<UserDto>.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We inject the RestClient.Builder that Spring Boot auto-configures, build a client with a baseUrl, and write restClient.get().uri("/users/{id}", id).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).retrieve().onStatus(status -> status.value() == 404, (req, res) -> { throw new NotFoundException(id); }).body(UserDto.class). We use toEntity(UserDto.class) instead of body() when we need the status or headers, and without onStatus a 4xx or 5xx would throw HttpClientErrorException or HttpServerErrorException.
Why this question is asked
Calling another service and turning its 404 into our own exception is one of the most common pieces of code in a Spring service, and it is a good test of whether we know the RestClient API well enough to write it without looking it up. Interviewers often ask for it as a small coding exercise and then ask about generic types. In this answer, we will build the client from Spring Boot's builder, write the call line by line with the reason for each step, see what happens without onStatus, test it with MockRestServiceServer, and finish with reading a List<UserDto>.
1Building the Client From Spring Boot's Builder
Spring Boot auto-configures a RestClient.Builder bean. It already contains the application's message converters, so JSON uses the same ObjectMapper settings as the rest of the app, and it is wired for observability, so our calls appear in metrics and traces. We inject it and set what is specific to this downstream service: the base URL.
Notice that we build the client once, in the constructor, and keep it in a field. A RestClient is thread-safe and meant to be reused; building one per call would waste work and lose connection reuse. In a real service we would also set a request factory with timeouts here, as the auto-configured one may not have the values we want.
2Writing the Call Step by Step
Now the method itself. Each line of the chain has one job.
- Send GET /users/42with the Authorization header
- Does an onStatus predicate match?YesRun our handler: 404 -> NotFoundExceptionNoGo to the default handler
- Is the status 4xx or 5xx?YesThrow HttpClientErrorException or HttpServerErrorExceptionNoDecode the body
- body(UserDto.class)JSON converted with the app's
ObjectMapper
4 steps in order. Play them, or step through them one at a time.
The URI uses a template with {id} instead of string concatenation. The reason is twofold: RestClient encodes the value safely, and metrics record the template /users/{id} rather than one entry per user id, which would explode the number of metric series. The header line sets a bearer token; .headers(h -> h.setBearerAuth(token)) is an equivalent shortcut.
onStatus takes a predicate on the status code and a handler. When the predicate matches, the handler runs, and throwing from it ends the call with our exception. We compare with status.value() == 404; status.isSameCodeAs(HttpStatus.NOT_FOUND) is another readable option. Finally body(UserDto.class) converts the JSON into our record.
3What Happens Without onStatus
If we leave out onStatus, the default status handler takes over. A 404 becomes HttpClientErrorException.NotFound, a 401 becomes HttpClientErrorException.Unauthorized, a 503 becomes HttpServerErrorException.ServiceUnavailable. All of them extend RestClientResponseException, which carries getStatusCode(), getResponseHeaders() and getResponseBodyAsString().
That default is safe, but it leaks HTTP details into the caller. Code that calls getUser() would have to catch a Spring web exception and check its status to know the user does not exist. With our handler, the caller catches NotFoundException, a domain exception that says what happened in business terms, and the HTTP details stay inside UserClient.
4When We Need Status or Headers: toEntity()
Sometimes the body is not enough, for example when the response carries an ETag for caching or a rate-limit header. Then we replace body() with toEntity(), which returns a ResponseEntity. The status handlers still apply, so a 404 still throws our exception.
5Testing the Call With MockRestServiceServer
MockRestServiceServer can bind to a RestClient.Builder. It replaces the request factory, so no real HTTP happens, and it lets us assert on the request and script the response.
Notice that we bind before UserClient builds its RestClient, so the client picks up the mock factory. One test per status we care about, 200, 404 and one 5xx, documents the behaviour of the client completely.
6Follow-up questions
How do you read a generic type such as List<UserDto>?
Java erases generic types at runtime, so List<UserDto>.class does not exist and body(List.class) would give us a list of maps. We pass a ParameterizedTypeReference instead, an anonymous subclass that captures the full type: restClient.get().uri("/users").retrieve().body(new ParameterizedTypeReference<List<UserDto>>() {}). The same works with toEntity() and with response.bodyTo() inside exchange().
Should the token be passed into every call?
For a user's own token being forwarded, passing it per call or reading it from the security context in an interceptor are both common. For service-to-service credentials, an interceptor on the builder that adds the header, for example one that obtains OAuth2 client-credentials tokens, is better, because no business method has to know about tokens and they are less likely to end up in logs.
What if the 404 response has a body we want to read?
The handler receives the response, so we can read it there, for example with response.getBody() or by decoding a problem details document, and put the details into our exception.
7Conclusion
In this answer, we wrote a RestClient call that fetches GET /users/{id} into a UserDto. We built the client once from Spring Boot's auto-configured RestClient.Builder with a baseUrl, used a URI template, set the bearer token with the Authorization header, turned 404 into NotFoundException with onStatus, and decoded with body(UserDto.class) or toEntity() when status and headers matter. Without onStatus, 4xx and 5xx raise HttpClientErrorException or HttpServerErrorException, and a ParameterizedTypeReference reads generic types such as List<UserDto>.
Open with
I inject the RestClient.Builder that Spring Boot auto-configures, because it already has the app's message converters and observability, and in the constructor I build the client once with baseUrl set to the users service and keep it in a field.
Then, if they want more
Then the method is restClient.get, uri with the template slash users slash {id} and the id, so the value is encoded and metrics see the template instead of one series per id. Then header with HttpHeaders.AUTHORIZATION and Bearer plus the token, or headers with setBearerAuth.
Then retrieve, and onStatus with a predicate status.value equals 404 and a handler that throws new NotFoundException(id). Finally body(UserDto.class). If I also need the status or headers, say an ETag, I use toEntity(UserDto.class) instead, and the status handler still applies.
Without onStatus, the default handler would throw HttpClientErrorException.NotFound for the 404, or HttpServerErrorException for 5xx, which works but leaks HTTP details to callers, so I prefer a domain exception. I test it with MockRestServiceServer bound to the builder, scripting 200, 404 and 500.
And for a list, since generics are erased, I pass a ParameterizedTypeReference of List of UserDto to body.
About this answer
- Last updated
- 12 November 2026
- 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.
- Official documentation
- Spring Framework reference, Spring Web MVC
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 a RestClient call that fetches GET /users/{id} into a UserDto, throws a custom...": https://scrivio-interview-library.netlify.app/spring-boot/http-clients/eee4ad448b/