How to reject the request and send custom message if extra params present in Spring boot REST Api

Viewed 888
@PostMapping()
public ResponseEntity<ApiResponse> createContact(
            @RequestBody ContactRequest contactRequest) throws IOException {
}

How to reject the API request, if extra params present in the request, by default spring boot ignoring extra parameters.

3 Answers

I believe you can add an HttpServletRequest as a parameter to the controller method (createContact in this case). Then you'll get access to all the parameters that come with the requests (query params, headers, etc.):

 @PostMapping
 public ResponseEntity<ApiResponse> createContact(HttpServletRequest request, 
 @RequestBody ContactRequest contactRequest) throws IOException {
        boolean isValid = ...// validate for extra parameters
        if(!isValid) {
            // "reject the request" as you call it...
        }
 }

First add an additional parameter to the method. This gives you access to information about the request. If Spring sees this parameter then it provides it.

@PostMapping()
public ResponseEntity<ApiResponse> createContact(
        @RequestBody ContactRequest contactRequest,
        WebRequest webRequest) throws IOException {

      if (reportUnknownParameters(webRequest) {
          return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
      }
}

I do something like this to get the bad request into the log.

private boolean reportUnknownParameters(WebRequest webRequest) {
    LongAdder unknownCount = new LongAdder();
    webRequest.getParameterMap().keySet().stream()
      .filter(key -> !knownParameters.contains(key))
      .forEach(key -> {
                 unknownCount.increment();
                 log.trace("unknown request parameter \"{}\"=\"{}\"", key, webRequest.getParameter(key));});
    return unknownCount.longValue() > 0;
}

add @RequestParam annotation in your methods parameter list and add it as a map, then you can access for it's key list and check if it contains anything else other than your required params.

public ResponseEntity<ApiResponse> createContact(@RequestParam Map<String,String> requestParams, @RequestBody ContactRequest contactRequest) throws IOException {
//Check for requestParams maps keyList and then pass accordingly.
 }
Related