Implementing Offset-Based Pagination
Make sure to check our introduction to pagination here !
Let us implement offset-based pagination in GraphQL. By the end of this tutorial, we should be able to return a sorted, filtered, and paginated list of users.
Let us model the User
type, which represents one user, with a name,
occupation, and age.
Let us now model the PaginationWindow
, which represents one βsliceβ of sorted,
filtered, and paginated items.
Note that PaginationWindow
is generic - it can represent a slice of users, or
a slice of any other type of items that we might want to paginate.
PaginationWindow
also contains total_items_count
, which specifies how many
items there are in total in the filtered dataset, so that the client knows what
the highest offset value can be.
Letβs define the query:
Now weβll define a mock dataset and implement the get_pagination_window
function, which is used by the users
query.
For the sake of simplicity, our dataset will be an in-memory list containing four users:
Hereβs the implementation of the get_pagination_window
function. Note that it
is generic and should work for all item types, not only for the User
type.
The above code first filters the dataset according to the given filters, then
sorts the dataset according to the given order_by
field.
It then calculates total_items_count
(this must be done after filtering), and
then slices the relevant items according to offset
and limit
.
Finally, it converts the items to the given strawberry type, and returns a
PaginationWindow
containing these items, as well as the total_items_count
.
In a real project, you would probably replace this with code that fetches from a
database using offset
and limit
.
If youβre using Strawberry with the Django web framework, you might want to make use of the Django pagination API. You can check it out here .
Running the Query
Now, let us start the server and see offset-based pagination in action!
You will get the following message:
Go to http://0.0.0.0:8000/graphql to open GraphiQL, and run the following query to get first two users, ordered by name:
The result should look like this:
The result contains:
-
items
- A list of the users in this pagination window -
totalItemsCount
- The total number of items in the filtered dataset. In this case, since no filter was given in the request,totalItemsCount
is 4, which is equal to the total number of users in the in-memory dataset.
Get the next page of users by running the same query, after incrementing
offset
by limit
.
Repeat until offset
reaches totalItemsCount
.
Running a Filtered Query
Letβs run the query again, but this time weβll filter out some users based on their occupation.
By supplying occupation: "ie"
in the query, we are requesting only users whose
occupation contains the substring βieβ.
This is the result:
Note that totalItemsCount
is now 3 and not 4, because only 3 users in total
match the filter.