I have a Spring REST API endpoint defined as follows:
@GetMapping("/books")
public List<Book> getBooks(
@RequestParam @NotNull Long id,
@RequestParam(required = false) String category) {
return libraryService.getBooks(id, category);
}
The category
parameter is optional, but when it is provided, I want to ensure it is not empty or null.
I attempted to use:
@RequestParam(required = false) @NotNull String category
because I read : /a/57818215/12769096, that the @required = false
stands only for the existence of the param itself, not for its value.
Which means it validates “&category” exists (or not) in the url, but doesn’t continue to check the value that assigned to it, which can be valid or null or empty or whatever.
But it caused conflicts, so I removed it, and right now it runs, apparently ok but without the validation that I want.
The issue is that currently, requests like:
https://library:8080/books?id=1234&category=
https://library:8080/books?id=1234&category=""
https://library:8080/books?id=1234&category
all result in a 500 Internal Server Error due to the invalid category value.
I want these requests to result in a 400 Bad Request instead (or whatever exception it thrown due to not answering the param constrains), as the category parameter exists but its value is invalid.
Requests without category should still pass without issues, as it now, because it’s optional.
How can I correctly validate the category parameter to achieve this behavior?