Module: APIResourcePaginatable

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

Overview

Helper To Make Resource APIs Paginatable

Paginating the requested items can avoid returning too much information in a single response. API callers can iterate over the results using pagination instead of rerteving all the data in one time, ruining the database connection or network.

There are two parameters clients can use: per_page and page. The former is used for setting how many data will be returned in each page, there will be a maxium limit and default value for each API:

GET /posts?per_page=10

The server will respond 10 items at a time.

Use the page parameter to specify which to retrieve:

GET /posts?page=5

Pagination info will be provided in the HTTP Link header like this:

Link: <http://api-server.dev/movies?page=1>; rel="first",
      <http://api-server.dev/movies?page=4>; rel="prev"
      <http://api-server.dev/movies?page=6>; rel="next",
      <http://api-server.dev/movies?page=238>; rel="last"

Line breaks are added for readability.

Which follows the proposed RFC 5988 standard.

Usage

Include this Concern in your Grape API class:

class SampleAPI < Grape::API
  include APIResourcePaginatable
end

then set the options for pagination in the grape method:

resources :posts do
  get do
    pagination User.count, default_per_page: 25, maxium_per_page: 100

    # ...
  end
end

Then use the helper methods, like this:

User.page(page).per(per_page)

HTTP Link header will be automatically set.

Defined Under Namespace

Modules: HelperMethods

Class Method Summary collapse

Class Method Details

.page_param_descObject

Return the 'page' param description


116
117
118
# File 'app/api/concerns/api_resource_paginatable.rb', line 116

def self.page_param_desc
  "Specify which page you want to get."
end

.per_page_param_descObject

Return the 'per_page' param description


111
112
113
# File 'app/api/concerns/api_resource_paginatable.rb', line 111

def self.per_page_param_desc
  "Specify how many items you want each page to return."
end