How To Handle Put Request in Rest Webservice

In the previous tutorial we saw how to handle DELETE request.  In this article we will see how to handle PUT request.  PUT request is used to submit data to REST service.  If the data is present it will be updated.  If the data is not there then it will be inserted.

PutService.java

The service method is annotated with @PUT which means it expects a PUT method.   The method matches the book id from the Book object received as parameter.  It then matches to see if the list contains the book id.  If it is present then it updates the book with the new name and returns the list.  If match is not found then it adds the book to the list and returns it.

package com.freetipscentral;
 
import java.util.ArrayList;
import java.util.List;
 
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
 
import com.freetipscentral.domain.Book;
 
@Path("/putBook")
public class PutService {
 
	List<Book> books = new ArrayList<Book>();
 
	@PUT
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	public Response deleteBook(Book book) {
		books = getBooks();
 
		for (Book book1 : books) {
			if (book1.getSerialNumber() == book.getSerialNumber()) {
				book1.setName(book.getName());
				return Response.ok(books).build();
			}
		}
 
		books.add(book);
		return Response.ok(books).build();
	}
 
	private List<Book> getBooks() {
		List<Book> books = new ArrayList<Book>();
		Book book1 = new Book();
		book1.setName("Head First Java");
		book1.setSerialNumber(1);
 
		Book book2 = new Book();
		book2.setName("Clean Coders");
		book2.setSerialNumber(2);
 
		books.add(book1);
		books.add(book2);
 
		return books;
	}
}

 

 

Book.java

package com.freetipscentral.domain;
 
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement
public class Book {
	String name;
	int serialNumber;
 
	public Book() {}
 
	public Book(String name, int serialNumber) {
		this.name = name;
		this.serialNumber = serialNumber;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public int getSerialNumber() {
		return serialNumber;
	}
 
	public void setSerialNumber(int serialNumber) {
		this.serialNumber = serialNumber;
	}
 
	public String toString() {
		return serialNumber + " "  + name;
	}	
}

Here are the input details

Headers

Content-Type : application/json

Accept : application/json

When the Input body is

{
 "name":"Harry Potter",
 "serialNumber": 2
 
}

 

Output is

[
{
"name": "Head First Java",
"serialNumber": 1
},
{
"name": "Harry Potter",
"serialNumber": 2
}
]

 

When the Input body is

{
 "name":"Harry Potter",
 "serialNumber": 3
 
}

Output is

[
{
"name": "Head First Java",
"serialNumber": 1
},
{
"name": "Clean Coders",
"serialNumber": 2
},
{
"name": "Harry Potter",
"serialNumber": 3
}
]