Filtering API results

When fetching a list of results it is common to filter down the data set based on some business criteria. For example, instead of listing all customers you may want to show only customers within a single company. Some APIs implement this filter as a sub-route. In general the Desk API implements this filtering ability not based on sub-routes but by use of the filter query parameter (also accepted via body parameter in a POST).

As often as possible we will make most fields (especially relationships) filterable, but there are cases where we simply cannot support filtering on certain fields (contains on body on threads for example). In these cases we usually have a search API endpoint to be used for full-text lookups.

Syntax

The following operators are supported:

const (
	Eq       Operator = "$eq"
	Ne       Operator = "$ne"
	Lt       Operator = "$lt"
	Lte      Operator = "$lte"
	Gt       Operator = "$gt"
	Gte      Operator = "$gte"
	In       Operator = "$in"
	Nin      Operator = "$nin"
	And      Operator = "$and"
	Or       Operator = "$or"
	Contains Operator = "$contains"
)

Examples

* Examples:
?filter={}
?filter={"age": 20}
?filter={"age": 20, "name": "mike"}
?filter={"age": {"$eq": 20}}
?filter={"age": {"$ne": 20}}
?filter={"age": {"$lt": 20}}
?filter={"age": {"$gt": 20}}
?filter={"age": {"$lte": 20}}
?filter={"age": {"$gte": 20}}
?filter={"age": {"$in": [20, 1]}}
?filter={"age": {"$nin": [20, 1]}}
?filter={"$or": [{"age":{"$gt": 20}}, {"name": "mike"}]}
?filter={"$or": [{"age":{"$gt": 20}}, {"name": "mike"}, {"$and": [{"age": {"$gt": 12}}, {"age": {"$lte": 18}} ]}]}
?filter={"$or": []}

* Supported operators
$eq             =
$ne             !=
$lt             <
$lte            <=
$gt             >
$gte            >=
$in             { qty: { $in: [ 5, 15 ] } }
$nin            !$in
$and            { $and: [ { price: 1.99 }, { qty: { $lt: 20 } }, { sale: true } ] }
implicit $and   { price: 1.99, qty: { $lt: 20 } , sale: true }
$or             { price:1.99, $or: [ { qty: { $lt: 20 } }, { sale: true } ] }

* Not supported
$all, $nor, $not, etc