I want to return an error when the body of a REST request is empty (e.g contains only {}
) but there is no way to detect if the request body contains an empty JSON or not.
I tried to change @RequestBody(required = true)
but it's not working.
@PatchMapping("{id}")
public ResponseEntity<Book> updateAdvisor(@PathVariable("id") Integer id,
@Valid @RequestBody BookDto newBook) {
Book addedBook = bookService.updateBook(newBook);
return new ResponseEntity<>(addedBook,HttpStatus.OK);
}
If the body sent contains an empty JSON I should return an exception. If the body is not empty and at least one element is provided I won't return an error.
Try @RequestBody(required = false)
This should cause the newBook
parameter to be null when there is no request body.
The above still stands and is the answer to the original question.
To solve the newly edited question:
@RequestBody BookDto newBook
parameter to a String parameter
(for example, @RequestBody String newBookJson
).@Autowired
private ObjectMapper objectMapper; // A Jackson ObjectMapper.
@PatchMapping("{id}")
public ResponseEntity<Book> updateAdvisor(
@PathVariable("id") Integer id,
@Valid @RequestBody String newBookJson)
{
if (isGoodStuff(newBookJson)) // You must write this method.
{
final BookDto newBook = ObjectMapper.readValue(newBookJson, BookDto.class);
... do stuff.
}
else // newBookJson is not good
{
.. do error handling stuff.
}
}