YK S
YK S

Reputation: 3440

Validating Query Params in REST API

I have a REST API which accepts query parameters. The query parameters are valid if and only if at a time only one query parameter is passed and it is among the list of valid query parameters.

Currently my logic for this is:

I am collecting the query params in a map. And then checking it's size. If size > 1 function throwing an error. If that is not the case then iterating through the map and if find a parameter other than valid ones the function throwing an error.

For example:

if(queryParam.size()>1) {
        throw new FailureResponse();
    }

queryParam.forEach(e->{
        String key = e.getKey();
        if(!key.equalsIgnoreCase("p1") && !key.equalsIgnoreCase("p2")) {
            throw new FailureResponse();
        }

    });

But I think in this way I am violating the SOLID design principle which says a class should be open for extension but closed for modification.

I also thought of creating a file and then reading the acceptable params from it but that would add to the response time of the API as it involves reading a file.

Is there some way I can keep and read the valid query-params and it does not violate the design principles?

Upvotes: 0

Views: 7767

Answers (1)

Aman J
Aman J

Reputation: 452

You could maintain an Enum of valid params and extend the enums as and when applicable like

public enum QueryParams{
      PARAM_1("param1"),
      PARAM_2("param2"),

      private String paramValue;
      QueryParams(String paramName){
        this.paramValue = paramValue();
      }
      public void getParamValue(){
         return this.value;
      }
}

and then you could iterate over the set of values of this enum to filter out invalid values

List<String> validParams = Arrays.asList(QueryParams.values()).stream().map(QueryParams::getParamValue).collect(Collectors.toList());
    queryParams.removeAll(validParams);
    if(queryParams.size()!=0) {
        throw new FailureResponse();
    }
}

This helps you maintain the API class without any changes, whenever a new parameter is added, just extend the enum and all the rest is automatically extended as it all depends upon the value in the enum.

Upvotes: 2

Related Questions