mituoh / api-pagination-1

Link header pagination for Rails and Grape APIs.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

api-pagination

Build Status Coverage Climate Dependencies gittip

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:

  1. Pull your collection from json: or xml:
  2. Use params[:page] and params[:per_page] to paginate your collection for you
  3. Use the paginated collection to render Link headers
  4. Call ActionController::Base#render with whatever you passed to paginate.

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
# ...

About

Link header pagination for Rails and Grape APIs.

License:MIT License


Languages

Language:Ruby 100.0%