Skip to content

jhannus/api_pagination_headers

 
 

Repository files navigation

#api_pagination_headers Build Status Dependency Status

api_pagination_headers is a gem that adds pagination info to a Link response header. This is considered to be the best practice for REST APIs and is currently used by GitHub. It also adds the total number of records into a Total-Count header.

Example:

Link: <http://example.com/posts?page=2&per_page=10>; rel="next", <http://example.com/posts?page=2&per_page=10>; rel="last"
Total-Count: 11

##Installation

Include in your Gemfile:

  • Rails 4
gem 'api_pagination_headers'
  • Rails 3.2
gem 'api_pagination_headers', branch: 'rails-3-2'

Depending on Kaminari or will_paginate at the moment. Support for rails-api is built in.

##Usage

In the controller:

  • Rails 4
class PostsController < ApplicationController
  after_action only: [:index] { set_pagination_headers(:posts) }

  def index
    @posts = Post.all.paginate(per_page: params[:per_page], page: params[:page])
    respond_with @posts
  end
end
  • Rails 3.2
class PostsController < ApplicationController
  after_filter only: [:index] { set_pagination_headers(:posts) }

  def index
    @posts = Post.paginate(per_page: params[:per_page], page: params[:page])
    respond_with @posts
  end
end

##Configuration

You can change the Total-Count header title by configuring the gem.

ApiPaginationHeaders.configure do |config|
  config.total_count_header = 'X-Total-Count'
end

##License Copyright © 2014 Richard Käll. Licensed under the MIT license.

About

Link header pagination for APIs.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Ruby 100.0%