简体   繁体   English

如何在REST API中实现过滤

[英]How to implement filtering in REST api

I am building a restful api's using spring mvc and spring jpa for database connection. 我正在使用spring mvc和spring jpa构建用于数据库连接的静态api。 I have requirement to create a get api which can filter the results based on filterString(passed as query parameter to GET request). 我需要创建一个get api,该API可以基于filterString(作为查询参数传递给GET请求的结果)过滤结果。

Example GET api for filter employee objects is 用于过滤员工对象的示例GET API是

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 目前,我正在通过使用regX解析filterString并从中创建“ spring jpa Specification”对象来实现此目的

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. 我见过很多支持这种过滤的REST API。 Can anyone suggest what is the best way to implement filtering on RESt server side? 谁能建议在RESt服务器端实现过滤的最佳方法是什么?

I use rsql-parser in my projects. 我在项目中使用rsql-parser I parse the query string creating the criteria object or the sql query. 我解析创建条件对象或sql查询的查询字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM