0

I have following user details model that is used in POST & PUT controllers of /user resource.

public class UserDetails {
    @NotBlank
    private String username;

    @NotBlank
    private String password;

    @NotBlank
    private String firstName;

    @NotBlank
    private String lastName;

    @NotBlank
    private String nic;

    @NotNull
    private Integer roleId;
    
    // constructor & getters setters
}
@PostMapping("/org/employee")
public void createEmployee(@RequestBody EmployeeDetailsModel empDetails) {
    employeeService.createUser(empDetails);
}

@PutMapping("/org/employee")
public void updateEmployee(@RequestBody EmployeeDetailsModel empDetails) {
    employeeService.updateUser(empDetails);
}

Here, UserDetails has @NotNull & @NotBlank validations. POST would work fine because to create a user, all details are mandatory. But when updating with PUT, I don't need all properties of UserDetails to be filled.

So my questions are,

  • How this kind of scenarios are handled? Do we usually force clients to send all those details whether they are changed or not?
  • Is it possible to disable request body validation just for a particular endpoint or do I have to create separate model that looks the same but without validations?
s1n7ax
  • 2,750
  • 6
  • 24
  • 53

1 Answers1

1

Seeing your post I can infer that you are interested in modifying the resource Well to do this you should to use PATCH method instead of PUT. In PUT you need to send the entire data since it is intended for replacing the resource which is not in the case of the PATCH.

Well in case of the PUT or PATCH we need to ensure that we have an existing resource. Hence before saving it is necessary that we get the original resource from the data store. Then we can modify it with the help of the validation rules on the Entity itself.

so your code should be like.

Considering you have a repository class named as

EmployeeRepository

    @PutMapping("/org/employee/{id}")
    public void updateEmployee(@RequestBody EmployeeDetailsModel empDetails, @PathVariable("id") int id) {
        Optional<Employee> emp = employeeRepo.findById(id);
        if (emp.isPresent()) {
            // update the new values using setters
            // Finally update the resource.
            employeeService.updateUser(empDetails);
        } else {
            throw new ResourceNotFoundException("Your custom msg");
        }

    }

The repository code should be placed inside the service method ie updateUser but I have placed it here just for demonstration.

vijaydeep
  • 395
  • 3
  • 12
  • Not used to be a developer but I have never seen a RESTful service uses PATCH but apparently there is such a thing. Following helped me to get an idea https://stackoverflow.com/questions/28459418/use-of-put-vs-patch-methods-in-rest-api-real-life-scenarios https://www.baeldung.com/http-put-patch-difference-spring – s1n7ax Apr 11 '21 at 14:57