A Simple Python GET Script

kevinw
Community Contributor
5
8618

Hey guys, 

I'll spare you my life story on this one, but I am the LMS Administrator at a non-profit institution. What that means is that I'm the administrator, the course designer, the data-analyst, the help team, and all things betwixt. I've had to learn about APIs from the ground up. Since most of the content in here is geared toward advanced users, I thought I would post something for the user who is just getting started. 

Step One - Get access token

Step One

The first thing you need when performing any API operation is an access token. You have to have administrative rights to do this. The good news is that you can auto-generate them yourself. Click on account - settings. Scroll down until you come to this and generate a new access token. 

Step Two

This step is the script itself. Python has a library available to make API requests. Naturally, this is called "requests". The documentation for this library can be found here.  There are several low priced books also available on Google-Play-Books. These books all assume some level of basic knowledge but if you want to further explore it, then they are good resources. Below is a picture of the script.

Python Code

The first part, URL, is the URL you are making your request to. The next and most important section is your headers. This is where you need your access token, or your request will never work. The part that is blurred it is where you will copy & paste your access token. 

After that, we use the variable r to form our request. This is where the library comes in handy. Here, we call our URL and use the headers to access it. Then we tell python to print our results. In this case, I have them printed in text and json format. The results are printed below. 

GET Result

The point of this is that it works. It returns your result with no hiccups. The next step of this project for me, personally, is to have these results saved to a CSV file that I can easily analyze. But the point of this is that it works. 

There are many useful things you can do with API calls, including POSTS, that allow you to create a course, delete a course, create and delete users, without ever having to access Canvas itself. 

5 Comments
dbalbieran
Community Novice

This was useful! Hope to see more projects in the future! thanks

stuart_ryan
Community Novice

That is a great guide nice work  @kevinw ! It is always awesome to share knowledge to help others out!

jschaffer
Community Champion

 @kevinw ‌,

I love python.  I have found it very intuitive and a very useful language for the tasks that I complete.  If you are interested in learning more about the language and how it can be used to retrieve, store, and manipulate data, there is a great open source book you can find online (Automate the Boring Stuff with Python ).  This book is not only free, but it helped to give me a good understanding of the basics of the python language and allowed me to get comfortable coding. 

I hope this helps. 

cljtech
Community Novice

I will be working on my first API soon and found this to be very helpful.

brian1441
Community Explorer

Hello,
I’ve been using the canvasapi module in python to write scripts that allow me to interact with courses and course objects. Now I’m trying to search through question banks, which don’t seem to be supported by the API. I thought I would try using the requests library. Your posting seemed to be just the thing I was looking for.

At first I was delighted to see html code streaming into my terminal window. But looking closer at the html this seems to be a login page. I don’t seem to be able to access our Canvas instance with this code. Which is odd since I’m offering the requests library the same access key that has worked for me when using the API. Please let me know if you notice anything wrong with the code as I typed it. Please let me know if there's a reason why the access code would work when accessing a course through the canvasapi library, but not through the requests library.

Here is the code as I typed it:

import config #-- my api key is in this file.
import requests

url = config.API_URL
headers = {'Authorization' : 'Bearer ' + config.API_KEY}



r = requests.get(url, headers = headers)

print(r.status_code)
print(r.text)

Here is the response I got:

>>> print(r.status_code)
200
>>> print(r.text)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Canvas Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="" />
<meta name="author" content="" />

<!-- Test for saved preference and redirect before loading page, saves ~100ms -->
<script>
var host = "https://canvas.uw.edu",
cookie_name = "canvas_wayf_preference",
saved_idp,
login_urls = {};

if (window.location.href.match(/-(test|beta)$/)) {
host = "https://uw." + RegExp.$1 + ".instructure.com";
}
login_urls["weblogin_option"] = host + "/login/saml/83";

function getCookie(name) {
var cookieValue, cookies, cookie, i;
if (document.cookie && document.cookie !== "") {
cookies = document.cookie.split(";");
for (i = 0; i < cookies.length; i++) {
cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) == name + "=") {
cookieValue = decodeURIComponent(
cookie.substring(name.length + 1)
);
break;
}
}
}
return cookieValue;
}

function setCookie(name, value, expire_days) {
var cookie_value,
expires_date = new Date();
expires_date.setDate(expires_date.getDate() + expire_days);
cookie_value =
escape(value) +
(expire_days === null
? ""
: "; expires=" + expires_date.toUTCString() + "; path=/");
document.cookie = name + "=" + cookie_value;
}

function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null
? ""
: decodeURIComponent(results[1].replace(/\+/g, " "));
}

if (getParameterByName("reset") === "1") {
setCookie(cookie_name, "", -1);
} else {
saved_idp = getCookie(cookie_name);
if (saved_idp !== undefined && login_urls.hasOwnProperty(saved_idp)) {
if (saved_idp === "weblogin_option") {
window.location.href = login_urls[saved_idp];
}
}
}
</script>

<!-- bootstrap 5.1.3 + icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css" rel="stylesheet" >

<link rel="shortcut icon" href="/img/favicon.ico" />
<link href="/styles/main.css" rel="stylesheet" />

</head>
<body>

<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-12 col-lg-6">
<div class="rounded-3 shadow form-signin p-4 pt-5" role="main">

<!-- begin content here -->
<h1 class="visually-hidden" id="login_header">UW Canvas login</h1>
<form class="mt-5">

<p class="text-light">You are required to sign in to your account:</p>

<div class="d-flex flex-wrap justify-content-between my-5 mx-auto" style="width:95%;">
<div class="form-check mb-3">
<input class="form-check-input" type="radio" name="idp_option" id="uw_login" value="weblogin_option" checked>
<label class="form-check-label" for="uw_login">
<img
src="/img/NetID-logo-reverse-200x80.png"
class="img-fluid"
alt="Login with your UW NetID"
/>
</label>
</div>
<div class="form-check mb-0">
<p class="text-light"><br/>
You can no longer sign in to UW Canvas or Panopto using a commercial Gmail account. <a href="https://itconnect.uw.edu/tools-services-support/teaching-learning/canvas/canvas-policies/access/gmai...">Learn more</a>.
</p>
</div>
</div>

<div class="d-flex justify-content-between">

<div class="form-check mb-3">
<input class="form-check-input" id="remember_option" type="checkbox" >
<label class="pe-3 text-light" for="remember_option">
Remember me for this browser
</label>
</div>

<div class="text-end text-nowrap">
<button id="login" type="submit" class="btn btn-light">
<i class="bi bi-arrow-right-circle-fill"></i>
Login
</button>
</div>
</div>

</form>
</div>

</div>
</div>


</div>
<!-- /container -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#login")
.click(function (ev) {
var selected_idp = $("input[name=idp_option]:checked").val();
ev.preventDefault();

if ($("#remember_option").is(":checked")) {
setCookie(cookie_name, selected_idp, 999);
}
window.location.href = login_urls[selected_idp];
})
.focus();
});
</script>
</body>
</html>

>>>


Thank you!