api-pagination
Paginate in your headers, not in your response body.
Installation
In your Gemfile
:
# Requires Rails (Rails-API is also supported) or Grape.
gem 'rails', '>= 3.0.0'
gem 'rails-api'
gem 'grape'
# Then choose your preferred paginator from the following:
gem 'kaminari'
gem 'will_paginate'
# Finally...
gem 'api-pagination'
Rails
In your controller, provide a pageable collection to the paginate
method:
class MoviesController < ApplicationController
# GET /movies
def index
movies = Movie.all # Movie.scoped if using ActiveRecord 3.x
paginate json: movies
end
# GET /movies/:id/cast
def cast
actors = Movie.find(params[:id]).actors
# Override how many Actors get returned. If unspecified,
# params[:per_page] (which defaults to 25) will be used.
paginate json: actors, per_page: 10
end
end
paginate
will:
- Pull your collection from
json:
orxml:
- Use
params[:page]
andparams[:per_page]
to paginate your collection for you - Use the paginated collection to render
Link
headers - Call
ActionController::Base#render
with whatever you passed topaginate
.
The collection sent to paginate
must respond to your paginator's methods. For Kaminari, Kaminari.paginate_array
will be called for you behind-the-scenes. For WillPaginate, you're out of luck unless you somewhere require 'will_paginate/array'
. Because this pollutes Array
, it won't be done for you automatically.
Grape
Grape is similar, though paginate
won't take options. Only your collection. In your API endpoint:
class MoviesAPI < Grape::API
format :json
desc 'Return a paginated set of movies'
paginate
get do
# This method must take an ActiveRecord::Relation
# or some equivalent pageable set.
paginate Movie.all
end
route_param :id do
desc "Return one movie's cast, paginated"
# Override how many Actors get returned. If unspecified,
# params[:per_page] (which defaults to 25) will be used.
paginate per_page: 10
get :cast do
paginate Movie.find(params[:id]).actors
end
end
end
Then curl --include
to see your header-based pagination in action:
$ curl --include 'https://localhost:3000/movies?page=5'
HTTP/1.1 200 OK
Link: <http://localhost:3000/movies?page=1>; rel="first">,
<http://localhost:3000/movies?page=173>; rel="last">,
<http://localhost:3000/movies?page=6>; rel="next">,
<http://localhost:3000/movies?page=4>; rel="prev">
Total: 4321
# ...