Paginate through large result set

I can query an API that returns a link header which includes the following data:

<>; rel="current", <>; rel="next", <>; rel="first", <>; rel="last"

The link header contains an indicator called “rel=“next”” that will only exist if there’s a next page and the corresponding page number tells me what it will be.

My trouble is that I’m trying to loop through the pages to add all of the paginated results to a JSON that can be output to another program for processing.

In my head I want to do something like:
if the API is called the first time then page number should always be 1, if a header comes back and the link header value contains “rel=“next”” then enter the corresponding page number with the next page header, if the header is there but no “rel=“next”” value then it knows its at the end.
For each of these loops it would need to add the body to an array that can be stored in memory or output to a directory.

I’m working within the Canvas API set if that helps.

I tried working though this community post but couldn’t get it to work.