1

According to this discussion - "RESTful API - Correct behavior when spurious/not requested parameters are passed in the request", we shouldn't ignore not requested parameters but how we can process this situation on all endpoint?

For example for this endpoint:

@RequestMapping(value = "/transactions/",
        method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public RestResultSupport getCommandsById(@PathVariable("id") String id) throws IOException {
    validateId(id);
    ....
    return result;
}

We'll get the same result for 2 different requests:

curl localhost:8080/?id=1200

and

curl localhost:8080/?id=1200&unknown=incorrect

If we imagine that we should process this situation on 20 endpoints, how can we simplify our code? Does Spring provide some tools for that?

Vladislav Kysliy
  • 3,488
  • 3
  • 32
  • 44

1 Answers1

0

I found only one way to do this - implement HandlerInterceptor.

Please have a look at an example:

public class RequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        Set<String> innerParams = request.getParameterMap().keySet();
        Set<String> describedParams = new HashSet<>();
        for (MethodParameter methodParameter : ((HandlerMethod) handler).getMethodParameters()) {
            if (methodParameter.hasParameterAnnotation(RequestParam.class)) {
                RequestParam requestParam = methodParameter.getParameterAnnotation(RequestParam.class);
                describedParams.add(requestParam.name());
            }
        }

        for (String inputRequestParam : innerParams) {
            if (!describedParams.contains(inputRequestParam)) {
                throw new BadDataException("Please provide valid request paramaters. [ Valid request parameters - " + describedParams + " ]");
            }
        }

        return true;
    }

... empty other required methods ...
}

Code analyzes required parameters and if it gets something unknown it will throw RuntimeException

Vladislav Kysliy
  • 3,488
  • 3
  • 32
  • 44