SlideShare a Scribd company logo
1 of 31
Automation using Scripting
and the Canvas API
David Lippman
Pierce College
Lumen Learning
Outline
• Quick overview of the Canvas API
• Why would we want to use it?
• Examples of scripting against the API
• Examples of scripting against export files
API
API = Application Programming Interface
A way for other programs to access data or
make changes in Canvas courses
https://canvas.instructure.com/doc/api/
API
“REST”: Basic GET/PUT/POST HTTP calls
JSON format return
https://domain.instructure.com/api/v1/courses
Authentication
HTTP Authorization Header
Send access token in the query string
https://domain.instructure.com/api/v1/courses?access_token=<ACCESS-TOKEN>
Generating a Token
Generating a Token
Scroll down…
Generating a Token
Generating a Token
So where does that get us?
or
Why should we care?
Use Case 1: Adding Attribution
Course with 100+ text pages
All needed a Creative Commons attribution
statement added
Option 1: Edit each by hand
Option 2: Modify an export file
Option 3: Use the API!
The General Idea
Call the page list.
https://domain.instructure.com/api/v1/courses/12345/pages
The General Idea
Call the page list. Repeat if needed.
$endpoint = “/api/v1/courses/$courseid/pages/”;
$itemlist = json_decode(
file_get_contents(
„https://‟.$domain.$endpoint.
„?per_page=50&page=„.$pagecnt.
„&access_token=„.$token
));
foreach ($itemlist as $item) {
$url = $item->url;
The General Idea
Grab the wiki page body.
The General Idea
Grab the wiki page body. Add attribution.
$endpoint = “/api/v1/courses/$courseid/pages/$url”;
$page = json_decode(
file_get_contents(
„https://‟.$domain.$endpoint.
„?access_token='.$token
));
$html = $page->body;
$html .= $attribution;
The General Idea
Send back
The General Idea
Send back using CURL
$endpoint = “/api/v1/courses/$courseid/pages/$url”;
$ch = curl_init(„https://‟.$domain.$endpoint.
„?access_token=‟.$token );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,
„wiki_page[body]=‟.urlencode($html));
$response = curl_exec($ch);
Time to Library-ize
require("canvaslib.php");
$api = new CanvasLMS($token,$domain);
$pages = $api->getPageList($courseid);
foreach ($pages as $id=>$name) {
$body = $api->getPageData($courseid, $id, 'body');
$body .= $attribution;
$api->updatePage($courseid, $id,
array("body"=>$body));
}
Use Case 2: Assignment Settings
Adding Instructions to all Assignments in a course
Use Case 2: Assignment Settings
$assn = $api->getAssignmentList($courseid);
foreach ($assn as $id=>$name) {
$api->updateAssignment($courseid, $id,
array(“description”=>$text));
}
Use Case 3: Fixing links
foreach ($pages as $id=>$name) {
$body = $api->getPageData($courseid, $id, 'body');
$body = str_replace(“oldsite.com”,“newsite.com”,
$body);
$api->updatePage($courseid, $id,
array("body"=>$body));
}
Use Case 4: Removing Links
foreach ($pages as $id=>$name) {
$body = $api->getPageData($courseid, $id, 'body');
$body = preg_replace(
'/<a[^>]*badsite[^>]*>(.*?)</a>/sm',
' $1 ', $body);
$api->updatePage($courseid, $id,
array("body"=>$body));
}
Use Case 5: Rehosting Images
preg_match_all(
„/images.badsite.com[^>]*(gif|png|jpg)/„,
$str, $matches);
foreach ($matches[0] as $m) {
$bn = basename($m);
cp(„http://‟.$m, ‟./imgs/‟.$bn);
$str = str_replace($m, „newhost.com/‟.$bn, $str);
}
General purpose, web-based tool
Append
Replace
Search-and-replace
Regex search-and-replace
http://www.imathas.com/canvas/canvassearch.html
Alternate Approach
Working with Exports
Upsides:
• Can be faster for large numbers of pages
• Can look at changes before uploading
Downsides
• Can’t be done on a live class
• Have to make sense of the file format
Working with Exports
• Canvas exports are based on Common
Cartridge
• Exports are renamed zip files
• Exports contain XML, HTML, and files
• Main file is imsmanifest.xml
– <resource> shows type and location of items
– <item> shows item structure (modules)
require("phpQuery-onefile.php");
$zip = new ZipArchive;
$zip->open($file);
phpQuery::newDocumentXML(
$zip->getFromName("imsmanifest.xml"));
$ref = pq("resource");
foreach ($ref as $r) {
$reflist[pq($r)->attr("identifier")] =
pq($r)->attr("href");
$reftype[pq($r)->attr("identifier")] =
pq($r)->attr("type");
}
$items = pq(“item”);
foreach ($items as $item) {
$iref = pq($item)->attr("identifierref");
if (isset($reftype[$iref]) &&
$reftype[$iref]=="webcontent") {
$filename = $reflist[$iref]);
$html = $zip->getFromName($filename);
$html = str_replace(„</body>‟,
$attribution.‟</body>‟, $html);
$zip->addFromString($filename, $html);
}
}
Sample Code
https://github.com/drlippman/canvas-scripts
• A simple library for doing API calls
• A sample program using the library
• The web-based general purpose tool
• Search-and-replace in a cartridge example

More Related Content

What's hot

ongc satellite communication
 ongc satellite communication ongc satellite communication
ongc satellite communicationNitin Tomar
 
Global positioning system
Global positioning systemGlobal positioning system
Global positioning systemArjun Manjooran
 
Dgps seminar
Dgps seminarDgps seminar
Dgps seminaranand0030
 
#2 gnss errors,its sources &amp; mitigation techniques
#2 gnss errors,its sources &amp; mitigation techniques#2 gnss errors,its sources &amp; mitigation techniques
#2 gnss errors,its sources &amp; mitigation techniquesMohammedHusain20
 
55166535 k-parameters-and-model-tuning
55166535 k-parameters-and-model-tuning55166535 k-parameters-and-model-tuning
55166535 k-parameters-and-model-tuningJamil Awan
 
GPS DOCUMENT
GPS DOCUMENTGPS DOCUMENT
GPS DOCUMENTTuhin_Das
 
Introduction to navstar gps
Introduction to navstar gpsIntroduction to navstar gps
Introduction to navstar gpsDocumentStory
 
Msp 430 addressing modes module 2
Msp 430 addressing modes module 2Msp 430 addressing modes module 2
Msp 430 addressing modes module 2SARALA T
 
Signal and telicommunication/sanjeet-1308143
Signal and telicommunication/sanjeet-1308143Signal and telicommunication/sanjeet-1308143
Signal and telicommunication/sanjeet-1308143sanjeet kumar
 
Global positioning system (gps)
Global positioning  system (gps)Global positioning  system (gps)
Global positioning system (gps)Vandana Verma
 
Gps tracking system
Gps tracking system Gps tracking system
Gps tracking system Sumit Kumar
 
Differential gps (dgps) 09 04-12
Differential gps (dgps) 09 04-12Differential gps (dgps) 09 04-12
Differential gps (dgps) 09 04-12Sumant Diwakar
 

What's hot (20)

ongc satellite communication
 ongc satellite communication ongc satellite communication
ongc satellite communication
 
BGP
BGPBGP
BGP
 
Global positioning system
Global positioning systemGlobal positioning system
Global positioning system
 
IRNSS
IRNSSIRNSS
IRNSS
 
Ppt satellite com.
Ppt satellite com.Ppt satellite com.
Ppt satellite com.
 
Dgps seminar
Dgps seminarDgps seminar
Dgps seminar
 
#2 gnss errors,its sources &amp; mitigation techniques
#2 gnss errors,its sources &amp; mitigation techniques#2 gnss errors,its sources &amp; mitigation techniques
#2 gnss errors,its sources &amp; mitigation techniques
 
55166535 k-parameters-and-model-tuning
55166535 k-parameters-and-model-tuning55166535 k-parameters-and-model-tuning
55166535 k-parameters-and-model-tuning
 
GPS DOCUMENT
GPS DOCUMENTGPS DOCUMENT
GPS DOCUMENT
 
Introduction to navstar gps
Introduction to navstar gpsIntroduction to navstar gps
Introduction to navstar gps
 
Msp 430 addressing modes module 2
Msp 430 addressing modes module 2Msp 430 addressing modes module 2
Msp 430 addressing modes module 2
 
Signal and telicommunication/sanjeet-1308143
Signal and telicommunication/sanjeet-1308143Signal and telicommunication/sanjeet-1308143
Signal and telicommunication/sanjeet-1308143
 
Global positioning system (gps)
Global positioning  system (gps)Global positioning  system (gps)
Global positioning system (gps)
 
Irnss ppt.
Irnss ppt.Irnss ppt.
Irnss ppt.
 
Gps
GpsGps
Gps
 
Gps
GpsGps
Gps
 
Satellite link design unit iii
Satellite link design unit  iiiSatellite link design unit  iii
Satellite link design unit iii
 
Gps tracking system
Gps tracking system Gps tracking system
Gps tracking system
 
Inertial navigation systems
Inertial navigation systemsInertial navigation systems
Inertial navigation systems
 
Differential gps (dgps) 09 04-12
Differential gps (dgps) 09 04-12Differential gps (dgps) 09 04-12
Differential gps (dgps) 09 04-12
 

Viewers also liked

Automating Canvas Applications Using Selenium
Automating Canvas Applications Using SeleniumAutomating Canvas Applications Using Selenium
Automating Canvas Applications Using Seleniumdavehunt82
 
Html5 canvas + sikuli + selenium 2 web driver
Html5 canvas + sikuli + selenium 2 web driverHtml5 canvas + sikuli + selenium 2 web driver
Html5 canvas + sikuli + selenium 2 web driverISsoft
 
Automating Canvas: difficult but possible
Automating Canvas: difficult but possibleAutomating Canvas: difficult but possible
Automating Canvas: difficult but possibleCOMAQA.BY
 
Test Automation Canvas - не наступайте на глабли автоматизации
Test Automation Canvas - не наступайте на глабли автоматизацииTest Automation Canvas - не наступайте на глабли автоматизации
Test Automation Canvas - не наступайте на глабли автоматизацииAndrey Rebrov
 
JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...
JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...
JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...Yusuke Yamamoto
 
Wso2 con raspberry-pi-cluster
Wso2 con raspberry-pi-clusterWso2 con raspberry-pi-cluster
Wso2 con raspberry-pi-clusterAfkham Azeez
 
Out of box page object design pattern, java
Out of box page object design pattern, javaOut of box page object design pattern, java
Out of box page object design pattern, javaCOMAQA.BY
 
5W2H (метод “7 вопросов”)
5W2H (метод “7 вопросов”)5W2H (метод “7 вопросов”)
5W2H (метод “7 вопросов”)SixSigmaOnline
 
QA Fest 2015. Артем Быковец. Техники тест дизайна или как правильно покрывать...
QA Fest 2015. Артем Быковец. Техники тест дизайна или как правильно покрывать...QA Fest 2015. Артем Быковец. Техники тест дизайна или как правильно покрывать...
QA Fest 2015. Артем Быковец. Техники тест дизайна или как правильно покрывать...QAFest
 
Артём Быковец "Bus Factor - или как контролировать и снижать процессные риски...
Артём Быковец "Bus Factor - или как контролировать и снижать процессные риски...Артём Быковец "Bus Factor - или как контролировать и снижать процессные риски...
Артём Быковец "Bus Factor - или как контролировать и снижать процессные риски...Fwdays
 
WSO2Con USA 2017: Iterative Architecture: A Pragmatic Approach to Digital Tra...
WSO2Con USA 2017: Iterative Architecture: A Pragmatic Approach to Digital Tra...WSO2Con USA 2017: Iterative Architecture: A Pragmatic Approach to Digital Tra...
WSO2Con USA 2017: Iterative Architecture: A Pragmatic Approach to Digital Tra...WSO2
 
Roman iovlev battle - JDI vs Selenide - Selenium Camp
Roman iovlev battle - JDI vs Selenide - Selenium CampRoman iovlev battle - JDI vs Selenide - Selenium Camp
Roman iovlev battle - JDI vs Selenide - Selenium CampРоман Иовлев
 

Viewers also liked (13)

Automating Canvas Applications Using Selenium
Automating Canvas Applications Using SeleniumAutomating Canvas Applications Using Selenium
Automating Canvas Applications Using Selenium
 
Html5 canvas + sikuli + selenium 2 web driver
Html5 canvas + sikuli + selenium 2 web driverHtml5 canvas + sikuli + selenium 2 web driver
Html5 canvas + sikuli + selenium 2 web driver
 
Automating Canvas: difficult but possible
Automating Canvas: difficult but possibleAutomating Canvas: difficult but possible
Automating Canvas: difficult but possible
 
Test Automation Canvas - не наступайте на глабли автоматизации
Test Automation Canvas - не наступайте на глабли автоматизацииTest Automation Canvas - не наступайте на глабли автоматизации
Test Automation Canvas - не наступайте на глабли автоматизации
 
Бизнес кейс
Бизнес кейсБизнес кейс
Бизнес кейс
 
JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...
JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...
JavaOne2016 #CON5929 Time-Saving Tips and Tricks for Building Quality Java Ap...
 
Wso2 con raspberry-pi-cluster
Wso2 con raspberry-pi-clusterWso2 con raspberry-pi-cluster
Wso2 con raspberry-pi-cluster
 
Out of box page object design pattern, java
Out of box page object design pattern, javaOut of box page object design pattern, java
Out of box page object design pattern, java
 
5W2H (метод “7 вопросов”)
5W2H (метод “7 вопросов”)5W2H (метод “7 вопросов”)
5W2H (метод “7 вопросов”)
 
QA Fest 2015. Артем Быковец. Техники тест дизайна или как правильно покрывать...
QA Fest 2015. Артем Быковец. Техники тест дизайна или как правильно покрывать...QA Fest 2015. Артем Быковец. Техники тест дизайна или как правильно покрывать...
QA Fest 2015. Артем Быковец. Техники тест дизайна или как правильно покрывать...
 
Артём Быковец "Bus Factor - или как контролировать и снижать процессные риски...
Артём Быковец "Bus Factor - или как контролировать и снижать процессные риски...Артём Быковец "Bus Factor - или как контролировать и снижать процессные риски...
Артём Быковец "Bus Factor - или как контролировать и снижать процессные риски...
 
WSO2Con USA 2017: Iterative Architecture: A Pragmatic Approach to Digital Tra...
WSO2Con USA 2017: Iterative Architecture: A Pragmatic Approach to Digital Tra...WSO2Con USA 2017: Iterative Architecture: A Pragmatic Approach to Digital Tra...
WSO2Con USA 2017: Iterative Architecture: A Pragmatic Approach to Digital Tra...
 
Roman iovlev battle - JDI vs Selenide - Selenium Camp
Roman iovlev battle - JDI vs Selenide - Selenium CampRoman iovlev battle - JDI vs Selenide - Selenium Camp
Roman iovlev battle - JDI vs Selenide - Selenium Camp
 

Similar to Automation using Scripting and the Canvas API

Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stackPaul Bearne
 
Extending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh PollockExtending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh PollockCaldera Labs
 
Designing REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDesigning REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDmitriy Sobko
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On RailsJohn Wilker
 
Using the SugarCRM REST API
Using the SugarCRM REST APIUsing the SugarCRM REST API
Using the SugarCRM REST APIAsa Kusuma
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin developmentMostafa Soufi
 
Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013Mohan Arumugam
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsMichael Peacock
 
Caldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW WorkshopCaldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW WorkshopCalderaLearn
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with PerlDave Cross
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Mario Cardinal
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryTatsuhiko Miyagawa
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Edureka!
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hackingJeroen van Dijk
 
David Keeney - SQL Database Server Requests from the Browser @ Postgres Open
David Keeney - SQL Database Server Requests from the Browser @ Postgres OpenDavid Keeney - SQL Database Server Requests from the Browser @ Postgres Open
David Keeney - SQL Database Server Requests from the Browser @ Postgres OpenPostgresOpen
 

Similar to Automation using Scripting and the Canvas API (20)

Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
 
Extending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh PollockExtending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh Pollock
 
Designing REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDesigning REST API automation tests in Kotlin
Designing REST API automation tests in Kotlin
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On Rails
 
Using the SugarCRM REST API
Using the SugarCRM REST APIUsing the SugarCRM REST API
Using the SugarCRM REST API
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin development
 
Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
Caldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW WorkshopCaldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW Workshop
 
Old WP REST API, New Tricks
Old WP REST API, New TricksOld WP REST API, New Tricks
Old WP REST API, New Tricks
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with Perl
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
 
Pyramid REST
Pyramid RESTPyramid REST
Pyramid REST
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
David Keeney - SQL Database Server Requests from the Browser @ Postgres Open
David Keeney - SQL Database Server Requests from the Browser @ Postgres OpenDavid Keeney - SQL Database Server Requests from the Browser @ Postgres Open
David Keeney - SQL Database Server Requests from the Browser @ Postgres Open
 

More from David Lippman

My Journey to Open - USNH ATI 2015
My Journey to Open - USNH ATI 2015My Journey to Open - USNH ATI 2015
My Journey to Open - USNH ATI 2015David Lippman
 
OER Update for FACTC Oct 2014
OER Update for FACTC Oct 2014OER Update for FACTC Oct 2014
OER Update for FACTC Oct 2014David Lippman
 
Automating Content Import
Automating Content ImportAutomating Content Import
Automating Content ImportDavid Lippman
 
Kaleidoscope Overview of Copyright
Kaleidoscope Overview of CopyrightKaleidoscope Overview of Copyright
Kaleidoscope Overview of CopyrightDavid Lippman
 
Open Course Library presentation, AMATYC 2013
Open Course Library presentation, AMATYC 2013Open Course Library presentation, AMATYC 2013
Open Course Library presentation, AMATYC 2013David Lippman
 
Santa Ana Open Math Forum
Santa Ana Open Math ForumSanta Ana Open Math Forum
Santa Ana Open Math ForumDavid Lippman
 
Understanding Copyright and Remixing by Example
Understanding Copyright and Remixing by ExampleUnderstanding Copyright and Remixing by Example
Understanding Copyright and Remixing by ExampleDavid Lippman
 

More from David Lippman (9)

My Journey to Open - USNH ATI 2015
My Journey to Open - USNH ATI 2015My Journey to Open - USNH ATI 2015
My Journey to Open - USNH ATI 2015
 
OER Update for FACTC Oct 2014
OER Update for FACTC Oct 2014OER Update for FACTC Oct 2014
OER Update for FACTC Oct 2014
 
The Case for Open
The Case for OpenThe Case for Open
The Case for Open
 
Automating Content Import
Automating Content ImportAutomating Content Import
Automating Content Import
 
Kaleidoscope Overview of Copyright
Kaleidoscope Overview of CopyrightKaleidoscope Overview of Copyright
Kaleidoscope Overview of Copyright
 
Open Course Library presentation, AMATYC 2013
Open Course Library presentation, AMATYC 2013Open Course Library presentation, AMATYC 2013
Open Course Library presentation, AMATYC 2013
 
Santa Ana Open Math Forum
Santa Ana Open Math ForumSanta Ana Open Math Forum
Santa Ana Open Math Forum
 
Understanding Copyright and Remixing by Example
Understanding Copyright and Remixing by ExampleUnderstanding Copyright and Remixing by Example
Understanding Copyright and Remixing by Example
 
Denver
DenverDenver
Denver
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 

Automation using Scripting and the Canvas API

  • 1. Automation using Scripting and the Canvas API David Lippman Pierce College Lumen Learning
  • 2. Outline • Quick overview of the Canvas API • Why would we want to use it? • Examples of scripting against the API • Examples of scripting against export files
  • 3. API API = Application Programming Interface A way for other programs to access data or make changes in Canvas courses https://canvas.instructure.com/doc/api/
  • 4. API “REST”: Basic GET/PUT/POST HTTP calls JSON format return https://domain.instructure.com/api/v1/courses
  • 5. Authentication HTTP Authorization Header Send access token in the query string https://domain.instructure.com/api/v1/courses?access_token=<ACCESS-TOKEN>
  • 10.
  • 11. So where does that get us? or Why should we care?
  • 12. Use Case 1: Adding Attribution Course with 100+ text pages All needed a Creative Commons attribution statement added Option 1: Edit each by hand Option 2: Modify an export file Option 3: Use the API!
  • 13. The General Idea Call the page list. https://domain.instructure.com/api/v1/courses/12345/pages
  • 14. The General Idea Call the page list. Repeat if needed. $endpoint = “/api/v1/courses/$courseid/pages/”; $itemlist = json_decode( file_get_contents( „https://‟.$domain.$endpoint. „?per_page=50&page=„.$pagecnt. „&access_token=„.$token )); foreach ($itemlist as $item) { $url = $item->url;
  • 15. The General Idea Grab the wiki page body.
  • 16. The General Idea Grab the wiki page body. Add attribution. $endpoint = “/api/v1/courses/$courseid/pages/$url”; $page = json_decode( file_get_contents( „https://‟.$domain.$endpoint. „?access_token='.$token )); $html = $page->body; $html .= $attribution;
  • 18. The General Idea Send back using CURL $endpoint = “/api/v1/courses/$courseid/pages/$url”; $ch = curl_init(„https://‟.$domain.$endpoint. „?access_token=‟.$token ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, „wiki_page[body]=‟.urlencode($html)); $response = curl_exec($ch);
  • 19. Time to Library-ize require("canvaslib.php"); $api = new CanvasLMS($token,$domain); $pages = $api->getPageList($courseid); foreach ($pages as $id=>$name) { $body = $api->getPageData($courseid, $id, 'body'); $body .= $attribution; $api->updatePage($courseid, $id, array("body"=>$body)); }
  • 20. Use Case 2: Assignment Settings Adding Instructions to all Assignments in a course
  • 21. Use Case 2: Assignment Settings $assn = $api->getAssignmentList($courseid); foreach ($assn as $id=>$name) { $api->updateAssignment($courseid, $id, array(“description”=>$text)); }
  • 22. Use Case 3: Fixing links foreach ($pages as $id=>$name) { $body = $api->getPageData($courseid, $id, 'body'); $body = str_replace(“oldsite.com”,“newsite.com”, $body); $api->updatePage($courseid, $id, array("body"=>$body)); }
  • 23. Use Case 4: Removing Links foreach ($pages as $id=>$name) { $body = $api->getPageData($courseid, $id, 'body'); $body = preg_replace( '/<a[^>]*badsite[^>]*>(.*?)</a>/sm', ' $1 ', $body); $api->updatePage($courseid, $id, array("body"=>$body)); }
  • 24. Use Case 5: Rehosting Images preg_match_all( „/images.badsite.com[^>]*(gif|png|jpg)/„, $str, $matches); foreach ($matches[0] as $m) { $bn = basename($m); cp(„http://‟.$m, ‟./imgs/‟.$bn); $str = str_replace($m, „newhost.com/‟.$bn, $str); }
  • 25. General purpose, web-based tool Append Replace Search-and-replace Regex search-and-replace http://www.imathas.com/canvas/canvassearch.html Alternate Approach
  • 26. Working with Exports Upsides: • Can be faster for large numbers of pages • Can look at changes before uploading Downsides • Can’t be done on a live class • Have to make sense of the file format
  • 27. Working with Exports • Canvas exports are based on Common Cartridge • Exports are renamed zip files • Exports contain XML, HTML, and files • Main file is imsmanifest.xml – <resource> shows type and location of items – <item> shows item structure (modules)
  • 28.
  • 29. require("phpQuery-onefile.php"); $zip = new ZipArchive; $zip->open($file); phpQuery::newDocumentXML( $zip->getFromName("imsmanifest.xml")); $ref = pq("resource"); foreach ($ref as $r) { $reflist[pq($r)->attr("identifier")] = pq($r)->attr("href"); $reftype[pq($r)->attr("identifier")] = pq($r)->attr("type"); }
  • 30. $items = pq(“item”); foreach ($items as $item) { $iref = pq($item)->attr("identifierref"); if (isset($reftype[$iref]) && $reftype[$iref]=="webcontent") { $filename = $reflist[$iref]); $html = $zip->getFromName($filename); $html = str_replace(„</body>‟, $attribution.‟</body>‟, $html); $zip->addFromString($filename, $html); } }
  • 31. Sample Code https://github.com/drlippman/canvas-scripts • A simple library for doing API calls • A sample program using the library • The web-based general purpose tool • Search-and-replace in a cartridge example

Editor's Notes

  1. Before we start:Open up Canvas to a course with a few items in itOpen up general search-and-replace tool. Put in course ID and token