Skip to content

What is a cursor?

So you're new to cursors? Fear not, we've got you covered.

Many APIs include endpoints that allow you to fetch items from a list, however, they often don't return all the items at once. Instead, they return a chunk of items from the list and send you back a cursor.

The cursor is like a bookmark, it tells us where we're up to, or how far we are through the list of items. When we want to get the next chunk of items from the list we send the cursor with our next request to the API, so that it knows where to get the next chunk of items from.

Imagine the API we're using has information on 100 books. We want to fetch this data, so we make a request to get the books:

result = api.get_books()
print(result.data)

Let's take a look at what the api responded with:

{
    "data": [
        {"title": "Book 1", ...},
        {"title": "Book 2", ...},
        ...
        {"title": "Book 20", ...},
    ],
    "nextCursor": 20
}

Interesting, it only sent us the first 20 books, but it did also send us a nextCursor.

Let's use the nextCursor to get more books.

result = api.get_books(cursor=20)
print(result.data)
{
    "data": [
        {"title": "Book 21", ...},
        {"title": "Book 22", ...},
        ...
        {"title": "Book 40", ...},
    ],
    "nextCursor": 40
}

Great, it sent us the next 20 books, and another nextCursor we can use to get more books.

Viola, this is how you can use a cursor to iterate over a list of items via API.