JAX-RS Client API simple DELETE example

In this post under JAX-RS Client, I will show with example how to perform a DELETE REST call.

Below is the complete code for your reference

Main Class


1  package defaultPackage;
2  
3  import jakarta.ws.rs.client.Client;
4  import jakarta.ws.rs.client.ClientBuilder;
5  import jakarta.ws.rs.client.Invocation;
6  import jakarta.ws.rs.client.WebTarget;
7  import jakarta.ws.rs.core.Response;
8  
9  public class Example4 {
10     public static void main(String[] args) {
11         Client client = ClientBuilder.newClient();
12         WebTarget webTarget = client.target("https://jsonplaceholder.typicode.com/users/10");
13         Invocation.Builder builder = webTarget.request();
14         Invocation invocation = builder.buildDelete();
15         Response response = invocation.invoke();
16         if(response.getStatus() == 200) {
17             System.out.println("Successful");
18             String result = response.readEntity(String.class);
19             System.out.println(result);
20         } else {
21             System.out.println("Failed");
22         }
23         client.close();
24     }
25 }

In the above code, at line 11, we create an instance of “Client” class using “ClientBuilder” class.

At line 12, we create an instance of “WebTarget” using the instance of “Client” created at line 11. We will also pass the url of the resource to be deleted as argument to “target” method of “Client” instance.

At line 13, we create an instance of “Invocation.Builder” class using “WebTarget” instance created at line 12.

At line 14, we create an instance of “Invocation” by calling “buildDelete” on the builder instance.

At line 15, we call “invoke” method on “Invocation” instance, which will return a “Response” object.

At line 16, we check the HTTP status and take action based on the status.

AT line 23, we close the “client” instance.

In this way, we can make a DELETE REST call to a resource.

Leave a Reply