I have a REST endpoint accepting some request parameters (let's call them one
and two
), all optional.
I would like to send a 400 Bad Request
response if one of them is misspelled (say tow
instead of two
). That would be the same thing as checking for unexpected parameters (like three
).
So I would send 200
on:
GET /
GET /?one=1
GET /?two=2
GET /?one=1&two=2
And I would send 400
on:
GET /?tow=2
GET /?three=3
How could I do this easily with Spring? I know how to specify expected parameters, but what about the unexpected ones?
My first idea was to have some sort of dictionary of allowed values and check it explicitly, but I would have to do this on every request method. There's got to be a better way.
@RestController
public class StrictController {
private static final String[] ALLOWED_PARAMS = { "one", "two" };
@GetMapping
@ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<Object> strict(
@RequestParam(name = "one", required = false) String one,
@RequestParam(name = "two", required = false) String two,
HttpServletRequest request) {
Enumeration<String> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
if (!paramAllowed(paramNames.nextElement())) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
}
return ResponseEntity.ok(null);
}
private boolean paramAllowed(String paramName) {
for (String allowedName : ALLOWED_PARAMS) {
if (allowedName.toLowerCase().equals(paramName.toLowerCase())) {
return true;
}
}
return false;
}
}
If you want to try this out, I have a MVCE.