Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advanced paging, sorting and filtering in REST API design

Tags:

rest

In REST API, it is considered a good practice to handle sorting, filtering and pagination of collections using URI query parameters, like:

GET /employees?offset=30&limit=15&name=Mary&sort=-surname

Unfortunately, in some "advanced" cases, the number of parameters may "explode", so that this solution is not possible any more.

Back to the previous example, suppose that we want to apply some more sophisticated filters on many other fields (eg.: address contains "NY", age > 30, age <= 40, (marital status is "married" AND salary<100000USD) OR (marital status is "divorced" AND salary>=100000USD), and many other... ).

Clearly, in such a case, a simple set of query parameters is not suitable.

How such a situation should be designed? Maybe the client should send a POST containing some structured data representing the query? Is there any more-or-less standard agreement on how to design such queries?

Thanks!

like image 974
Starnuto di topo Avatar asked Mar 19 '17 22:03

Starnuto di topo


2 Answers

One approach is to make search filters a REST resource meaning creating new REST methods:

  • POST /filters, expecting a body with filters, e.g. (marital status is "married" AND salary<100000USD) OR (marital status is "divorced" AND salary>=100000USD) and returning the unique id of this search, and (to avoid a roundtrip to the server) the first results, and links to the next results
  • GET /filters/<id>/<offset>, returning the results for search id starting from offset
like image 109
Adam Siemion Avatar answered Oct 24 '22 20:10

Adam Siemion


Have you tried posting a body with filters?

{
  "age": {
    "$gte": 30,
    "$lte": 40
  },
  "status": {
    "$in": [
        "Divorced",
        "Single"
    ]
  }
}
like image 45
imgr8 Avatar answered Oct 24 '22 20:10

imgr8