Week 2 of GSoC I had the task of implementing paginated APIs in Open Event project. I was aware that DRF provided such feature in Django so I looked through the Internet to find some library for Flask. Luckily, I didn’t find any so I decided to make my own.
A paginated API is page-based API. This approach is used as the API data can be very large sometimes and pagination can help to break it into small chunks. The Paginated API built in the Open Event project looks like this -
Let me explain what the keys in this JSON mean -
start- It is the position from which we want the data to be returned.
limit- It is the max number of items to return from that position.
next- It is the url for the next page of the query assuming current value of
previous- It is the url for the previous page of the query assuming current value of
count- It is the total count of results available in the dataset. Here as the ‘count’ is 128, that means you can go maximum till start=121 keeping limit as 20. Also when you get the page with start=121 and limit=20, 8 items will be returned.
results- This is the list of results whose position lies within the bounds specified by the request.
Now let’s see how to implement it. I have simplified the code to make it easier to understand.
Just to be clear, here I am assuming you are using SQLAlchemy for the database. The
klass parameter in the above code is the SqlAlchemy db.Model class on which you want
to query upon for the results. The
url is the base url of the request, here ‘/api/v2/events/page’ and it used in setting the previous and next urls.
Other things should be clear from the code.
So this was how to implement your very own Paginated API framework in Flask (should say Python). I hope you found this post interesting.
Until next time.