Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Thu Dec 28 2023

Send payload in DELETE request in RestTemplate

I was working on a new micro service the other day, and I came across a scenario where I wanted to send a body in a DELETE request to a third party API. I have done this many times before in e.g NodeJs using Axios - which has never been a problem. But when I was using RestTemplate in my Spring Boot application, I came across some issues. In this short guide, I will share my solution to the problem with the hope that anyone could find this helpful.

Solution

In my project, I have a helper class that I call RequestHelper where I have setup a bunch of helper methods for firing requests. And for my DELETE helper method, I solved the issue with the payload by simple converting my payload object to a JSON string using Jackson.

public <T, K> K delete(String url, T payload, Class<K> classType, HttpHeaders headers) throws JsonProcessingException { RestTemplate template = new RestTemplate(); String jsonPayload = new ObjectMapper().writeValueAsString(payload); HttpEntity<String> requestEntity = new HttpEntity<>(jsonPayload, headers); ResponseEntity<K> entity = template.exchange(url, HttpMethod.DELETE, requestEntity, classType); return entity.getBody(); }

And the consume it like this - where Payload and ResponseBody is the classes of your choice.

Payload p = new Payload(); delete("https://some.api/delete", p, ResponseBody.class, headers);

And that's it. Now the payload should be sent appropriatly.

Summary

This was it for this short guide - hope you found this helpful and that it could help you with your DELETE requests in Spring Boot.

All the best,

signatureThu Dec 28 2023
See all our articles