Constructing Filters

Begin by adding a filters parameter to your URL. Its value should be a JSON object with two keys: match and rules.

The value for match should be either "and" or "or":

  • "and": all records retrieved will match all of your filters.
  • "or": all records retrieved will match at least one of your filters.

The value for the rules key must be a JSON array of objects, where each object is a filter. Most filters consist of three key-value pairs:

  1. field: the key of the field you want to filter by - e.g. “field_1”
  2. operator: the operator for the filter, like “is” or “contains”
  3. value: the value that the operator uses to filter by

Note that filters which do not require values through the Builder or front end do not require them in API calls (e.g., “is blank,” “is not blank,” etc.)

Let's take a look at a JavaScript example from the Contact Directory template app, where we specify that a company's name must be either "Dodgit" or blank.

// Request route
var api_url = 'https://api.knack.com/v1/objects/object_1/records';

// Prepare filters
var filters = {
  'match': 'or',
  'rules': [
             {
               'field':'field_1',
               'operator':'is',
               'value':'Dodgit'
             },
             {
               'field':'field_1',
               'operator':'is blank'
             }
           ]
};

// Add filters to route
api_url += '?filters=' + encodeURIComponent(JSON.stringify(filters));

Note that filters for date ranges have two additional variables: range and type:

var api_url = 'https://api.knack.com/v1/objects/object_1/records';

// field_3 is a date/time field
var filters = [
  // Filter for records with a value for this field in the last three months
  {
    "field":"field_3",
    "operator":"is during the previous"
    "range":3,
    "type":"months"
  }
];

// Add filters to route
api_url += '?filters=' + encodeURIComponent(JSON.stringify(filters));

What’s Next