AnsweredAssumed Answered

I need help with PHP curl post updates to a course

Question asked by Wes Matchett on Jul 2, 2019
Latest reply on Jul 3, 2019 by Wes Matchett

I have just started using the API; I need to integrate an internal SIS with Canvas.  I have written an initial PHP class that I am using to verify how to use the API.  I can get data fine, but when I post a change it isn't sticking.  Here is the class..

 

class CanvasAPI
{
  private $client_id;
  private $apiURLBase;
  private $access_token;
  private $ch = NULL;

 

  public function __construct( $url, $token, $id )  {
    $this->apiURLBase = $url;
    $this->access_token = $token;
    $this->client_id = $id;
  }

 

  private function execute( $url, $post=false, $payload=array() )  {
    $this->ch = curl_init($this->apiURLBase.$url);
    curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, TRUE);
    $headers[] = 'Accept: application/json';
    $headers[] = 'Authorization: Bearer ' . $this->access_token;
    curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
    if($post) {
      print_r($payload);
      curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($payload));
    }
    $results = json_decode(curl_exec($this->ch));
    if( curl_error($this->ch) ) {
      echo curl_error($this->ch).PHP_EOL;
      error_log( curl_error($this->ch) );
    }
    return $results;
  }

 

  public function getCourse( $course_id ) {
    return $this->execute("/courses/".$course_id);
  }

 

  public function updateCourse( $course_id, $updates ) {
    $payload = array( 'course' => $updates );
    return $this->execute("courses/".$course_id,  true, $payload );
  }
}

and the calling code (sans the base class and the token). I have used several constants here to siplify the code (ie. course id)...

 

$canvasAPI = new CanvasAPI($apiURLBase, $access_token, $client_id);
$updates = array (
  'start_at' => '2019-06-01T00:00:00Z',
  'end_at' => '2019-07-31T23:59:59Z',
  'sis_course_id' => "CRS5" )
$canvasAPI->updateCourse('91', $updates );
$course = $canvasAPI->getCourse('91');
printf("%s (%s)".PHP_EOL, $course->name, $course->sis_course_id );

 

and the output.  The array output is the payload being sent in the updateCourse post.Tthe last line is the title and sis_course_id retrieved with the getCourse request, showing the sis_course_id was not updated...

 

Array
(
    [course] => Array
        (
            [start_at] => 2019-06-01T00:00:00Z
            [end_at] => 2019-07-31T23:59:59Z
            [sis_course_id] => CRS5
        )

)
20th Century History (CRS1)

 

Any ideas about what I am doing wrong?

Outcomes