Search code examples
spring-bootannotationsentity

Spring Boot: How to make a field as mandatory in POST request while in PUT request it should be optional


I am using entity class.

Consider a field "Name" is mandatory in request body for POST request and for updating i.e., in PUT request that "Name" field should be optional.

We don't need to pass the "Name" field again it is not necessary.

So I want to make "Name" attribute mandatory in POST request body and optional in PUT request body.


Solution

  • You can use groups parameter in JSR303 annotations.

    @NotEmpty annotation applies when accessed via "Existing" interface:

    public class Greeting {
    
      private final long id;
      @NotEmpty(groups = Existing.class)
      private final String content;
    
      public Greeting(long id, String content) {
          this.id = id;
          this.content = content;
      }
    
      public long getId() {
          return id;
      }
    
      public String getContent() {
          return content;
      }
    
      public interface Existing {
      }
    }
    

    Note @Validated(Existing.class) annotation on PutMapping

    @PostMapping("/greeting")
    public Greeting newGreeting( @RequestBody Greeting gobj) {
        return new Greeting(counter.incrementAndGet(),
                String.format(template, gobj.getContent()));
    }
    
    @PutMapping("/greeting")
    public Greeting updateGreeting(@Validated(Existing.class) @RequestBody Greeting gobj) {
        return new Greeting(gobj.getId(),
                String.format(template, gobj.getContent()));
    }
    

    For above example Json body {"id": 1} will work for POST but for PUT you will get HTTP 400 telling you that "content parameter must not be empty". {"id": 1, "content":"World"} will be accepted for both methods.