How do you use Guzzle to iterate through several pages of a paginated API response?

Viewed 195

I'm attempting to consume a REST API using the PHP library Guzzle.

The API results are paginated by the server, meaning they only return 20 rows at a time.

Pages are navigated by sending a current_page parameter e.g. current_page=2.

A typical response might look like this:

// First page of results
// Notice the lack of the "current_page" attribute
{
    "items": [
        {...},
        {...},
        {...} // etc
    ],
    "search_criteria": {
        "filter_groups": [],
        "page_size": 20
    },
    "total_count": 197
}

// Second page
// Notice the presence of the "current_page" attribute
{
    "items": [
        {...},
        {...},
        {...}
    ],
    "search_criteria": {
        "filter_groups": [],
        "page_size": 20,
        "current_page": 2
    },
    "total_count": 197
}

Is there a way that Guzzle can automatically iterate through all pages of the response without me having to clutter up the code with a for loop and manually calculate the current page figures etc.?

0 Answers
Related