I am building a restful api's using spring mvc and spring jpa for database connection. I have requirement to create a get api which can filter the results based on filterString(passed as query parameter to GET request).
Example GET api for filter employee objects is
http://localhost:8080/api/v1/employee?filter="(firstName eq john) and (lastName eq doe) or (empId eq 123)"
Currently I am achieving this by parse the filterString using regX and create the "spring jpa Specification" object from it
Below is the code snippet
public List<Employee> searchEmployee(String filter) throws Exception {
// filter = "/"(firstName eq john) and (lastName eq doe) or (empId eq 123)/""
// remove the " characters from start and end
filter = filter.replaceAll("^\"|\"$", "");
// spit the string basis of and/or
String[] value = filter.split("(((?<=or)|(?=or)))|(((?<=and)|(?=and)))");
Specification specs = null;
String op = null;
for (String f : value) {
if (!"or".equalsIgnoreCase(f) && !"and".equalsIgnoreCase(f)) {
String[] p = f.trim().split("\\s{1,}");
if (p != null && p.length == 3) {
EmployeeSpecification es = new EmployeeSpecification(new SearchCriteria(p[0], p[1], p[2]));
if (specs == null ) {
specs = Specification.where(es);
} else {
if ("or".equalsIgnoreCase(op)) {
specs = specs.or(es);
} else if ("or".equalsIgnoreCase(op)) {
specs = specs.and(es);
}
}
} else {
throw new Exception("Invalid search criteria");
}
} else {
op = f;
}
List<Employee> l = empDao.findAll(specs);
return l;
}
I have seen many REST api's which support the filtering like this. Can anyone suggest what is the best way to implement filtering on RESt server side?
GraphQLorRestQL, despite the name implication, you won't achieve REST (in its true sense) with such things, and REST doesn't need such things actually. A server that allows a client to filter certain aspects will provide clients with either forms that teach a client on which fields are available for filtering or provide a set of URIs a client can chose from to retrieve the filtered state it is interested in. Nowhere should a REST client be forced to use any external documentation or DSL to retrieve what it is interested in