Hands-On RESTful Web Services with TypeScript 3
上QQ阅读APP看书,第一时间看更新

Filtering

Sometimes, a resource contains more data than is needed by the requester. In this case, the API should have the ability to filter elements in or out from the resource.

Filter in or out doesn't mean that the resource will change. Remember that GET methods are idempotent. It will only remove from the response, but the original information will still be available.

Filtering can be implemented as a query parameter that's named for the field to be filtered on. The value needs to be the value it needs to filter for. You can refer to the definition of filtering at https://jsonapi.org/recommendations/#filtering.

For example, the following is a request for all items associated with a particular order with a name of coffee:

GET http://<HOST>/order/<id>/items?filter[name]=coffee

Also, multiple filter values could be combined in a comma-separated list:

GET http://<HOST>/order/<id>/items?filter[name]=coffee,milk

Furthermore, multiple filters can also be applied to the same request as another filter:

GET http://<HOST>/order/<id>/items?filter[name]=coffee,milk&filter[category]=organic

There is also the possibility to include the following operators:

  • in: Getting items within the range between 5 and 20:
GET http://<HOST>/order/<id>/items?filter[size]=in:5,20
  • nin: Getting items that are out of a range:
GET http://<HOST>/order/<id>/items?filter[size]=nin:5,20
  • neq: Getting items not matching a specific value:
GET http://<HOST>/order/<id>/items?filter[category]=neq:built-in
  • gt: Getting items greater than a specific value:
GET http://<HOST>/order/<id>/items?filter[size]=gt:5
  • gte: Getting items greater than a specific value, inclusive:
GET http://<HOST>/order/<id>/items?filter[size]=gte:5
  • lt: Getting items lower than a specific value:
GET http://<HOST>/order/<id>/items?filter[size]=lt:25
  • lte: Getting items lower than a specific value, inclusive:
GET http://<HOST>/order/<id>/items?filter[size]=lte:25