Pagination is a solved problem in web frameworks, where you commonly page through lots of records. But what about the API side? How do you page through data there?
- [Instructor] Paginating is a common problem in web applications, and it's pretty easy to solve with a modern web framework. But what about for an API? How do we paginate an API? And doesn't it seem like it'd be really hard? Well, luckily Laravel provides a few tricks for us to get this working. Let's open up our polls controller class in app Http Controllers PollsController.php. Let's change the get call on line 14 to paginate. So now our line reads return response json Poll paginate and a 200.
At this point now we can save this file, we can start up our PHP artisan server, open up Insomnia, and we'll call our get polls method. Notice our polls are displayed along with the meta data about the pagination response. We have a current page, we have a data, which includes all of our polls, and at the bottom we have the first_page_url from last_page, last_page_url, next page, the path, the previous page, the to, the total.
This shows us the meta data that we need, i.e., the data about the data itself that we need to be able to paginate through each of our responses and paginate through our polls. Let's go back to our controller and see how we can actually paginate through. We'll update Poll paginate to only return one response at a time by passing into our paginate method the value one. This'll only show one record at a time. Save this and go back to Insomnia, and resend the request, and we'll see here we only get back one poll.
Notice we get back information to tell us how to get to the next page. We can pass it in with adding in ?page=2. We send this and we get back our second poll, and notice it tells us how to get to the next page or even the last page by passing in page is equal to 12. So we get back to our last page. Notice it even shows us how to get to the previous page URL with page is equal to 11. So we can keep paginating through our API as often as we need to.
Notice it should be easy for someone to access your API and use that next_page_url meta data field to page through the API and pull up as many records as they need, or use any of the other meta data provided in the pagination response to be able to figure out exactly how to get the data that they need.
- Reviewing the basics of an API
- Basic pieces of the Laravel framework
- Reading, adding, editing, and deleting a record
- API errors and exceptions
- Transforming your API data
- Returning nested and sideloaded data
- Creating a logging middleware
- Authenticating to your API
- Basic and advanced endpoint testing