SergioGregorutti's avatar

REST API - Pagination best practice

Hi all,

Im working on a REST API and I have a question.

For example, I have an endpoint to get all categories: /api/categories

Can I use the same endpoint to get all categories but paginated? Im thinking on something like: /api/categories?paginated=true

But I dont know if there's a best practice to do this.

What do you think? If someone has a suggestion will be great.

Thanks in advance!

0 likes
6 replies
pmall's avatar

I would do /api/categories?start=10&end=20 so you get a slice of your categories

SergioGregorutti's avatar

@pmall So, if there's no "start" and "end" parameters I will get all categories without pagination? And if I have the parameters I get the list paginated?

pmall's avatar

What you mean by list paginated ? Whay you want is a slice of articles from a page no ? you can also do /api/categories?page=2 so you get the second page categories

willvincent's avatar

This ought to work...

get('api/categories', function(\Illuminate\Http\Request $request) {
  $num_per_page = 5;
  if ($request->input('paged')) {
    return App\Category::paginate($num_per_page)->appends('paged', $request->input('paged'));
  }

  return App\Category::all();
});

Note: The appends() method is necessary otherwise next/previous links generated by the pager won't include the flag to indicate results should be paged.

MAnasShakoor's avatar

use the paginate query builder and it will handel every thing in the query

Please or to participate in this conversation.