REST PUT with Example – RESTful Web Services Tutorial

2 years ago Lalit Bhagtani 0

In REST PUT is a method level annotation, this annotation indicates that the following method will respond to the HTTP PUT request only. It is used to create or update a resource. PUT annotated method puts a resource at a specific URI, if a resource is already present at that URI then PUT replace or update that resource and if resource is not present at that URI, then it creates a new one. URI for PUT request will always point to a specific resource ( <base URL>/<resource-name>/{resource-id} ), for example, if resource is book then URI will be <base URL>/books/1 and it will update or create a new resource ( book ) on this URI.

PUT operation is idempotent which means, if PUT operation is repeated multiple times ( hit same URI multiple times ) for same set of values then it will produce the same result ( state of resource would be same ). PUT responses are not cacheable.

Let’s try to understand it with an example.

REST PUT method Example  :-

In this example of REST PUT, 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.


public class PutMethodExample {
    public Response getAllBooks(@PathParam("id") String bookId,String bookName){
	return Response.status(200)
		       .entity("Book id is : " + bookId + " and name is : " + bookName).build();

Result :-


References :-

  1. @PUT Java Docs

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