Module: APIResourceFilterable

Extended by:
ActiveSupport::Concern
Included in:
API::APIDataManagement, API::Open
Defined in:
app/api/concerns/api_resource_filterable.rb

Overview

Helper To Make Resource APIs Filterable

A filterable resource API supports requests to filter resources according to specific criteria, using the filter query parameter.

For example, the following is a request for all products that has a particular color:

GET /products?filter[color]=red

With this approach, multiple filters can be applied to a single request:

GET /products?filter[color]=red&filter[status]=in-stock

Multiple filters are applied with the AND condition.

OR conditions of a single value can be represented as:

GET /products?filter[color]=red,blue,yellow

A few functions: not, greater_then, less_then, greater_then_or_equal, less_then_or_equal, between and like can be used while filtering the data, for example:

GET /products?filter[color]=not(red)
GET /products?filter[price]=greater_then(1000)
GET /products?filter[price]=less_then_or_equal(2000)
GET /products?filter[price]=between(1000,2000)
GET /products?filter[name]=like(%lovely%)

Usage

Include this Concern in your Grape API class:

class SampleAPI < Grape::API
  include APIResourceFilterable
end

then use the filter method like this:

resources :products do
  get do
    @products = filter(Post, filterable_fields: [:name, :price, :color])    # ...

  end
end

The filter method will return the scoped model, based directly from the requested URL. Further usage of this method can be found in the docs of the HelperMethods class.

Defined Under Namespace

Modules: HelperMethods

Class Method Summary collapse

Class Method Details

.filter_param_desc(for_field: nil) ⇒ Object

Return the 'fields' param description


120
121
122
123
124
125
126
# File 'app/api/concerns/api_resource_filterable.rb', line 120

def self.filter_param_desc(for_field: nil)
  if for_field.present?
    "Filter data base on the '#{for_field}' field."
  else
    "Filter the data."
  end
end