Skip to content

JsonApi filtering

Thomas Pollet edited this page Apr 27, 2021 · 3 revisions

Default Filter

The swagger shows the jsonapi filters that can be used in the url query arguments. Items with an exact match of the specified attribute value can be fetched by specifying the corresponding key-value query parameter. For example, suppose the User class, exposed at /Users has a name attribute, to retrieve all instances with the name "John", you can use a GET request to /Users?filter[name]=John.

It is also possible to use more generic filters by specifiying a JSON string, for example:

  • filter=[{"name":"timestamp","op":"gt","val":"2020-08-01"},{"name":"timestamp","op":"lt","val":"2020-08-02"}]
  • filter=[{"name":"name","op":"eq","val":"Author 0"}]

Each filter object has the following fields:

  • name: The name of the field you want to filter on.
  • op: The operation you want to use (all sqlalchemy operations are available). The valid values are:
    • eq: check if field is equal to something
    • ge: check if field is greater than or equal to something
    • gt: check if field is greater than to something
    • ne: check if field is not equal to something
    • is_: check if field is a value
    • is_not: check if field is not a value
    • le: check if field is less than or equal to something
    • lt: check if field is less than to something
  • val: The value that you want to compare.

Custom Filtering

It is possible to create custom filter methods that will be called with the filter= url query parameter argument as function arguments, for example:

class User(SAFRSBase, db.Model):

    id = db.Column(String, primary_key=True)
    username = db.Column(db.String(32))

    @classmethod
    def _s_filter(cls, *args, **kwargs):
        print(args, kwargs) # args[0] should contain the filter= url query parameter value
        return cls.query.filter_by(username = args[0])

The query results that are returned will be serialized as json:api objects.

Another way to implement custom filtering is by overriding SAFRSBase.jsonpai_filter, for example: https://github.com/thomaxxl/safrs/blob/master/examples/mini_examples/ex06_filtering.py