Spring Restful WS – HTTP PUT Request

Spread the love

In this tutorial, we will see what is a PUT request and how it is handled.

Client sends a PUT request when it wants to update something on an existing set of data or resource which is already present on the server.

Consider the below request sent by the client through POTSMAN UI to update employee details.

Consider the above PUT request. We are sending a JSON payload in the body and sending a Emp Id in the url (100).

Let’s implement the Sever Side PUT method handler in the REST controller.

Class EmployeeReqDetails
{
   private String name;
   private String age;
   private String designation;

.... public getters and setters
}

Class Employee
{
   private String empId;
   private String name;
   private String age;
   private String designation;

....public getters and setters

}

com.techfinanceworld.restapp.controller;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("employees")
public Class EmpController{

Map<String, Employee> emps;

   @PostMapping(produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE}) //line 4
   public ResponseEntity<Employee> CreateEmployee(@RequestBody EmployeeReqDetails erd) //line 5
   {
      Employee e = new Employee();
      e.setName(erd.getName());
      e.setAge(erd.getAge());
      e.setDesignation(erd.getDesignation());

      String empId = Math.random().toString();
      e.setEmpId(empId);

      if (emps = null){
        emps = new HashMap<>();
      }

      emps.put(empId,emp);
      return new ResponseEntity<Employee>(e,HttpStatus.OK);
 }

   @PutMapping(path = "/{empId}", produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE}) //line 4
   public Employee CreateEmployee(@PathVariable String empId, @RequestBody EmployeeReqDetails erd) //line 5
   {
      Employee e = emps.get(empId);
      e.setName(erd.getName());
      e.setAge(erd.getAge());
      e.setDesignation(erd.getDesignation());

      emps.put(empId,e);
      
      return e;
   }

}

As seen above, using POST request we are creating/adding the employees in the map and using PUT we are updating the employee details in the map.
After updation we are returning the employee object as a JSON response to the client.