Spring validation for optional request body

I use Java and Spring to create a post rest webservice. The service obviously has a request body, but it is declared as optional. If the request body is not supplied, the service expects a single query parameter to be supplied instead.

  • POST services/items with a request body will result in a new item to
    be created.
  • POST services/items?copyFromItem=123 without a request
    body will create a new item which is a copy of item 123.

I use spring’s @Valid annotation to valid the request body. The problem is that I want to allow the request body to be null/empty (in the copy item case) but unfortunately then I get validation errors. I cannot remove the @Valid annotation because in that case the body no longer gets validated when it IS supplied.

Here is the code snippet:

public CreateItemResponse createItem(
        @Valid @RequestBody(required = false) CreateItemRequest createItemRequest,
        @RequestParam(required = false) Long copyFromItem,
        final BindingResult bindingResult