Kaminari provides easy pagination in a rails app. It’s great to use. We’ll make it better by adding a little function to your controllers to provide useful pagination headers.
Pagination from Kaminari
Installation is easy with an addition to your
and an install:
Now, you have a magical
page method available on your models. It works like a charm right out of the box.
Let’s say that I have a
germs_controller.rb (because it’s a great time of year for that), where I have a list of germs that I want to paginate. I could easily request
/api/v1/germs?page=2 and get the second page with this code in the controller:
1 2 3 4 5 6 7 8 9 10
If you want to control the default page size, you can do that in the initializers:
1 2 3
There’s another feature that we want to add, and that’s pagination headers. These are going to be HTTP headers that come back in the response that indicate to clients where the relative pages are located in our API. For instance, we asked for page 2, but where might one request the previous and next pages, 1 and 3?
Putting the pagination info into the header follows a pattern used in the github api.
We’ll add a function to our
ApplicationController to helps us out:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
This code will provide a
Link header in the HTTP response. Its value might look something like this:
The values of
next, etc are populated from calls to Kaminari methods such as
In order to have this header set on a response, we need to add it to a callback in our controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Now, a fresh request to
/api/v1/germs with or without the
page query parameter should return back the
Link header in the HTTP response which your client can use to traverse the other pages of data available in your API.
So, there’s one way to get pagination info from Kaminari into your HTTP headers. What would you improve?