Provide pagination using a Link HTTP header as described in GitHub's REST API documentation.
This pagination style accepts a single page number in the request query parameters. The response uses an HTTP header called Link to provide the URLs for the next, previous, first, and last pages. If you are using Python's Requests library to make the request, this header is automatically parsed for you as described here.
Request:
GET https://api.example.org/accounts/?page=4
Response:
HTTP 200 OK
Link: <https://api.example.org/accounts/>; rel="first", <https://api.example.org/accounts/?page=3>; rel="prev", <https://api.example.org/accounts/?page=5>; rel="next", <https://api.example.org/accounts/?page=11>; rel="last"
[
{
"id": 1,
"name": "item one",
},
...
]
- Python (3.7+)
- Django (3.2+)
- Django REST Framework (3.11+)
Install using pip:
$ pip install drf-link-header-paginationAdd drf_link_header_pagination to your project's INSTALLED_APPS setting.
To enable the LinkHeaderPagination style globally, use the following configuration, modifying the PAGE_SIZE as desired:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'drf_link_header_pagination.LinkHeaderPagination',
'PAGE_SIZE': 100
}On GenericAPIView subclasses you may also set the pagination_class attribute to select LinkHeaderPagination on a per-view basis.
Other pagination classes that are available are:
LinkHeaderCursorPagination: This is similar to the normalCursorPaginationclass but using theLinkheader to return only thenextand/orprevlinks. Thefirstandlastlinks are unavailable.LinkHeaderLinkResponseCursorPagination: This is similar toLinkHeaderCursorPagination, but in addition to thenextand/orprevURL's being in theLinkheader, the content of the response body is updated to include them as well. The body will be an object with the keysnext(the next page's URL or None),previous(the previous page's URL or None), andresults(the original content of the body).LinkHeaderLimitOffsetPagination: Uses theLimitOffsetPaginationpagination class from DRF to supportoffsetandlimitparameters instead ofpageto indicate offset into the queryset.
The configuration is the same as for
PageNumberPagination.
Use the excellent tox testing tool to run the tests against all supported versions of Python and Django. Install tox globally, and then simply run:
$ tox