J-O Eriksson's Blog

Pieces of Py #6 Handling Paginated API Responses with the Walrus Operator

How to use the Python walrus operator (:=) to cleanly handle paginated API responses, with a real-world Microsoft Graph example.

Introduction

The walrus operator (:=), introduced in Python 3.8, lets you assign a value to a variable as part of an expression. This is particularly handy when working with paginated API responses, where each iteration needs to both extract the next page URL and decide whether to keep going.

Background

At work I do a lot of API calls to Microsoft Graph. Sometimes, if the result set is too large, the API returns a paginated response — the payload includes an @odata.nextLink field pointing to the next page. You keep fetching until that field is absent. I found this pattern is a natural fit for the walrus operator.

Example

Let’s say you want to fetch all members of a group. First, fetch the initial page and seed your results list:

import json

initial_response = get_graph_response(auth_token, initial_url)
response = json.loads(initial_response.text)
group_members_list = {"value": response["value"]}

Without the walrus operator

The traditional approach uses a while True loop with an explicit break:

while True:
    next_link = response.get("@odata.nextLink")
    if not next_link:
        break
    response = json.loads(get_graph_response(auth_token, next_link).text)
    group_members_list["value"].extend(response["value"])

This works, but while True gives no hint about when the loop stops — the exit condition is buried inside the body as a break.

With the walrus operator

while next_link := response.get("@odata.nextLink"):
    response = json.loads(get_graph_response(auth_token, next_link).text)
    group_members_list["value"].extend(response["value"])

The condition now says exactly what it means: keep looping as long as there is a next page. The assignment and the check happen in one place, and there’s one less variable to track inside the loop body.

Conclusion

The walrus operator isn’t just syntactic sugar here — it eliminates the while True / break pattern and makes the loop’s exit condition explicit and self-contained. If you’re working with any API that uses cursor- or link-based pagination, this is a clean way to express it.

Resources