AnsweredAssumed Answered

How to Interpret and Handle Pagination PHP cURL

Question asked by Larry Robertson on Apr 22, 2019
Latest reply on Apr 23, 2019 by Larry Robertson

I am new to Canvas.

I am confused when looking the link information returned in the header for pagination.

Recently the default per_page setting was changed from 30 to 100 (the max) I believe this was done by the admin.

I am retrieving the Sub-Accounts and there is a total of 69. In my code I am trying to get 10 at a time just to test pagination.  When I look at the Link portion of the header here is what I see (note that I changed all < and > to double quotes for display purposes:

 

link:
"https://canvas.instructure.com/api/v1/accounts/1/sub_accounts?page=1&per_page=10"; rel="current",
"https://canvas.instructure.com/api/v1/accounts/1/sub_accounts?page=2&per_page=10"; rel="next",
"https://canvas.instructure.com/api/v1/accounts/1/sub_accounts?page=1&per_page=10"; rel="first",
"https://canvas.instructure.com/api/v1/accounts/1/sub_accounts?page=7&per_page=10"; rel="last"

 

Shouldn't the next page be 11 and the last page be 10?

This is my first time dealing with pagination so maybe there is something that I missing here.

 

Here is my PHP Code:

 

<?php

// OPTIONS:
$url = 'https://canvas.instructure.com/api/v1/accounts/1/sub_accounts?per_page=10';
$curl = curl_init();
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . '<token>',
'Content-Type: application/json'
));

//curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

// EXECUTE:
$result = curl_exec($curl);
$result = str_replace("<",'"',$result);
$result = str_replace(">",'"',$result);
echo $result;

if(!$result){
die("Connection Failure");
}
curl_close($curl);

?>

 

My Goal

What I would like to do is to get all 69 records into an associative array so that I can do a mass update on the data and then PUT the new data.  I assume I could do this in a loop by

  1. Getting 10 at a time and appending to the array.
  2. Make the update
  3. Replacing the existing with the new.

Is this the wrong approach?

Outcomes