I’m back with another part of my tutorial for Django REST framework.
Today, I wanted to take a closer look at another issue: pagination.
Note 1: Throughout this article, I refer to this excellent source of best practices for a pragmatic RESTful API.
Note 2: You can find the project code we’re working on in this series in this repository.
Let’s now delve into the problem of pagination in the Django REST Framework.
Have a look at the standard answer at one of our endpoints.
We got a standard list of objects. So far, so good.
But what if our endpoint returns thousands of objects? The serialization and transmission of that amount of data may take long enough for the application user to notice a downtime.
We can solve this problem by including pagination; the division of results into pages of a fixed size. The best strategy here is using the limit + offset method, where the parameter `limit` passed in GET specifies the number of elements per page, and` offset` determines the offset in relation to the beginning of the list.
As you can see, the results were enveloped. This practice is justified when the client can’t handle HTTP headers, but it’s slowly becoming obsolete these days.
The most recent guides to best practices recommend the transmission of metadata in headlines while allowing enveloping on demand. We will implement this solution below.
The endpoint must return a list of objects in the same structure as initially.Pagination is carried out using the `limit` and` offset` parameters.
Additional metadata are included in the appropriate headings.
The code is to use packaging on demand (provided by the parameter).
The code always contains links in the headers – even if the version with the packaging has been chosen.
Note: There exists a django-rest-framework-link-header-pagination library, but it doesn’t implement the limit / offset mechanism which is of interest to us here.
The simplest solution will be inheriting the class rest_framework.pagination.LimitOffsetPagination because we have most of the logic implemented there.
To make it all work in line with best practices, we only need links to the first and last page.
Where to put all that code?
The best place to put this code is a separate file that can be easily imported from anywhere in the project.
You can also use the library I prepared with the code above by installing `pip install hedju` and later as DEFAULT_PAGINATION_CLASS you can use ‘hedju.HeaderLimitOffsetPagination’.
< Link: <http://127.0.0.1:8000/api/v1/friends/?limit=1&offset=1>; rel="next", <http://127.0.0.1:8000/api/v1/friends/?limit=1&offset=1>; rel="last"
That’s all, folks! In the next part, I’ll discuss the subject of filtering the data list.