Implementing search and sort operations

Allowing a client to perform the search and sort operations on a resource collection is very essential to improve the market adoption of your APIs. As there is no existing standard for passing sort criteria or search conditions, various API vendors follow different patterns. A very common approach is to pass the search and sort criteria as the query parameters to the server.

The following example illustrates how you can pass the search criteria as the query parameters to the server:

/employees?departmentName=hr&salary>500000 

The query parameters present in the preceding resource request URI can be used by the RESTful API implementation to find out the employee resources belonging to the HR department whose annual salary is greater than 500000.

Similarly, to read the collection of resources in a sorted order, you can pass the sort criteria as the query parameter to the API. The following example uses the sort keyword as the query parameter to indicate the beginning of fields in the URI for sorting, followed by the asc or desc keyword, indicating the sort order:

/employees?sort=firstName:asc,lastName:asc 

If you have complex search conditions that cannot be easily represented as the request parameter in the URI, you can consider moving the search conditions into the request body and use the POST method for issuing the search. Here is an example:

POST  employees/searches HTTP/1.1 
Host: packtpub.com 
Accept: application/json 
Content-Type: application/json 
{ 
  "criteria": [{ 
    "firstName": "A"; 
    "operator": "startswith" 
  }], 
  "sort": [{"firstName":"asc","lastName":"asc" } 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.180.43