REST API DELETE method with Example – RESTful Web Services Tutorial

7 years ago Lalit Bhagtani 0

In REST API DELETE is a method level annotation, this annotation indicates that the following method will respond to the HTTP DELETE request only. It is used to delete a resource identified by requested URI.

DELETE operation is idempotent which means. If you DELETE a resource then it is removed, gone forever. If you repeat the DELETE operation for that same resource, result will be same, “resource is deleted“. Response status is 200 ( OK ) for the first DELETE operation as this operation deletes the resource, for the successive DELETE operation response status will be 404 ( NOT FOUND ) as resource is already deleted by first DELETE operation.

Let’s try to understand it with an example.

REST API DELETE Example :-

In this example of REST API DELETE, we will hit this URL <base URL>/books/1 with name of the book in the body of the request. @Consume annotation is used to bind message in the body of the request to the method argument bookName.

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("books")
public class DeleteMethodExample {

    @DELETE
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.TEXT_PLAIN)
    @Path("/{id}")
    public Response getAllBooks(@PathParam("id") String bookId,String bookName){
        if("Harry Potter".equalsIgnoreCase(bookName)){
            return Response.status(200)
                           .entity("Book is deleted").build();
        }else{
            return Response.status(200)
                           .entity("Book is not deleted").build();
        }		
    }
	
}




Result :-

REST API DELETE

References :-

  1. @DELETE Java Docs

That’s all for REST API DELETE with Example. If you liked it, please share your thoughts in comments section and share it with others too.