Sub topic 6
Sending request bodies with POST, PUT and DELETE
This chapter covers the write side of RestClient: creating, replacing and deleting remote resources. It assumes you can already build a RestClient with a base URL (see "Creating and configuring a RestClient"). It also assumes you know how retrieve() reads a response. You should know the HTTP semantics of POST, PUT and DELETE, and be comfortable with Java records and Spring beans.
How a request with a body is built
A RestClient request is a chain of calls. For a request that carries a body, the chain has four parts:
- Pick the HTTP method with
post(),put(),patch()ordelete(). - Set the target with
uri(...). - Describe the body with
contentType(...)andbody(...). - Send the request and choose how to read the result with
retrieve()followed bybody(...),toEntity(...)ortoBodilessEntity().
Nothing is sent until you call a terminal method such as body(...), toEntity(...) or toBodilessEntity(). The client is synchronous, so the calling thread blocks until the response has arrived or a timeout fires.
POST: creating a resource
The object you pass to body(...) is converted by an HttpMessageConverter. With Spring Boot and Jackson on the classpath, a record becomes JSON. Always set contentType(...) yourself. Relying on the default makes the request depend on which converters happen to be registered, and it makes the code harder to read.
The example below uses three small records and returns the new todo together with the Location header the server sent back.
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClient;
class TodoWriter {
record Todo(long id, String title, boolean completed) {}
record NewTodo(String title) {}
private final RestClient restClient;
TodoWriter(RestClient todoRestClient) {
this.restClient = todoRestClient;
}
Todo create(NewTodo newTodo) {
ResponseEntity<Todo> response = restClient.post()
.uri("/todos")
.contentType(MediaType.APPLICATION_JSON)
.body(newTodo)
.retrieve()
.toEntity(Todo.class);
URI location = response.getHeaders().getLocation();
System.out.println("Created at " + location + " with status " + response.getStatusCode());
return response.getBody();
}
}toEntity(Todo.class) gives you the status code, the headers and the converted body. Use it when the status or a header matters, as Location does here. If only the body matters, body(Todo.class) is shorter.
Choosing the terminal method
| Terminal method | Returns | Use it when |
|---|---|---|
| `body(Class<T>)` | `T` | You only need the parsed body. |
| `body(ParameterizedTypeReference<T>)` | `T` | The body is a generic type such as `List<Todo>`. |
| `toEntity(Class<T>)` | `ResponseEntity<T>` | You need status or headers and the body. |
| `toBodilessEntity()` | `ResponseEntity<Void>` | You need status or headers and no body. |
body(...) can return null when the response has no content, for example after a 204 No Content. If you expect a body, check for null or use toEntity(...) and inspect the status.
PUT: replacing a resource
PUT sends the full representation of a resource to a known URI. The server replaces whatever it had at that URI. Because the URI identifies the resource, you build it with a template variable, as you did for GET.
record UpdatedTodo(String title, boolean completed) {}
void replace(long id, UpdatedTodo updated) {
restClient.put()
.uri("/todos/{id}", id)
.contentType(MediaType.APPLICATION_JSON)
.body(updated)
.retrieve()
.toBodilessEntity();
}Place this method inside the TodoWriter class above. Many APIs answer a PUT with 204 No Content, so toBodilessEntity() fits. If your API returns the stored resource with 200 OK, swap in body(Todo.class) or toEntity(Todo.class).
patch() follows exactly the same shape. Use it when the API accepts partial updates. Check the API's documentation for the content type it expects. Some APIs want application/merge-patch+json rather than plain application/json.
DELETE: removing a resource
DELETE normally has no request body, so the chain is shorter.
void delete(long id) {
restClient.delete()
.uri("/todos/{id}", id)
.retrieve()
.toBodilessEntity();
}You must still call a terminal method. A chain that ends at retrieve() does not send anything useful, because the request is only executed when you ask for a result.
Why idempotency matters here
HTTP defines PUT and DELETE as idempotent. Repeating the same request leaves the server in the same state. POST is not idempotent. Sending the same POST twice can create two resources. This matters as soon as you add retries, either in your own code or in an interceptor.
- A retry after a timeout on PUT or DELETE is normally safe.
- A retry after a timeout on POST can create a duplicate, because the first request may have succeeded before the response was lost.
- If the API supports an idempotency key header, send it on POST. The header name varies by provider, so read its documentation.
Other kinds of request bodies
Records are the common case, but body(...) accepts anything a registered converter can write.
Generic types
When the body is a generic type, the type information is lost at runtime. Pass a ParameterizedTypeReference as a second argument so the converter knows the element type.
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
void createMany(List<NewTodo> todos) {
restClient.post()
.uri("/todos/batch")
.contentType(MediaType.APPLICATION_JSON)
.body(todos, new ParameterizedTypeReference<List<NewTodo>>() {})
.retrieve()
.toBodilessEntity();
}For a plain List<NewTodo> Jackson usually serializes correctly without the type reference. The reference matters when elements are subclasses or when the converter relies on the declared type. Passing it costs nothing and removes the guesswork.
Form data
For application/x-www-form-urlencoded, use a MultiValueMap and set the matching content type.
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
void submitForm(String title) {
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
form.add("title", title);
restClient.post()
.uri("/todos/form")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(form)
.retrieve()
.toBodilessEntity();
}Strings and raw JSON
A String body is written as is. If you pass a JSON string, set contentType(MediaType.APPLICATION_JSON) yourself. Otherwise the string converter may label the request as text/plain, and many servers reject it.
Per-request headers
You can add headers to a single request without changing the shared client. This is useful for idempotency keys and conditional updates.
import org.springframework.http.HttpHeaders;
void replaceIfUnchanged(long id, UpdatedTodo updated, String etag) {
restClient.put()
.uri("/todos/{id}", id)
.header(HttpHeaders.IF_MATCH, etag)
.contentType(MediaType.APPLICATION_JSON)
.body(updated)
.retrieve()
.toBodilessEntity();
}If the server's version no longer matches the ETag, it usually answers 412 Precondition Failed. RestClient turns that into an exception. The next section's topic, error handling, explains how to catch it.
What happens when a write fails
By default, retrieve() throws an exception for any 4xx or 5xx status. Write operations hit this often. Common cases are:
400 Bad Requestor422 Unprocessable Entity: the body failed validation on the server.409 Conflict: the resource already exists or was changed by someone else.415 Unsupported Media Type: theContent-Typeis wrong for this endpoint.404 Not Foundon PUT or DELETE: the resource does not exist.
The exception is a subclass of RestClientResponseException, so you can read the status and the server's error body.
import org.springframework.web.client.RestClientResponseException;
boolean tryCreate(NewTodo newTodo) {
try {
create(newTodo);
return true;
} catch (RestClientResponseException e) {
System.err.println("Create failed: " + e.getStatusCode()
+ " " + e.getResponseBodyAsString());
return false;
}
}For finer control over particular statuses, use onStatus(...) on the chain, as shown in the chapter on error handling.
Common mistakes
- Forgetting the terminal call. A chain that stops at
retrieve()or earlier never produces a result. Always end withbody(...),toEntity(...)ortoBodilessEntity(). - Leaving out
contentType. The request may go out with an unexpected media type, and the server answers415. Set it every time. - Reading a body that is not there. Calling
body(Todo.class)after a204returnsnull. UsetoBodilessEntity()when you expect no content. - Concatenating ids into the URI string. Use
"/todos/{id}"with a variable so the value is encoded properly. - Mutating a shared client. The built
RestClientis immutable and safe to share across threads. Per-request headers set in a chain affect only that request.
Exercise
A service calls restClient.post().uri("/orders").contentType(MediaType.APPLICATION_JSON).body(order).retrieve() and then returns. The remote API never receives an order. What is wrong, and which two terminal methods would you choose between if the API answers 201 Created with a Location header and an empty body?
Show answer
The chain never calls a terminal method, so the request is not executed. Add one at the end. Because the response has no body but the Location header is needed, use toBodilessEntity() and read the header with response.getHeaders().getLocation(). toEntity(Order.class) would also work in code, but it tries to convert an empty body and gives nothing extra. Use body(Order.class) only when you need the parsed body and not the headers.
Exercise
Your team wants a retry interceptor on the shared RestClient. Which of the methods POST, PUT and DELETE are safe to retry after a read timeout, and what extra protection does POST need?
Show answer
PUT and DELETE are idempotent, so repeating them after a timeout leaves the server in the same state. POST is not, because the first attempt may have succeeded before the response was lost, and a retry can create a duplicate. For POST, send an idempotency key header if the API supports one, or avoid automatic retries.