Automating Course Completion to Auto-Enrollment with Live Events
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
Introduction:
Recently, I explored automating course enrollments in Canvas LMS—specifically, how to automatically enroll students into a follow-up course once they've completed a prerequisite. Canvas Live Events turned out to be an effective way to tackle this challenge, so I wanted to share my personal approach and a simple script I created as a proof-of-concept.
⚠️ Important Note: The code provided in this post is intended as a proof of concept and should not be deployed directly into large-scale production environments. This code is not officially supported by Instructure.
Tools and Technologies:
- Canvas Live Events
- Canvas API
- Python 3.x
- Flask
- Requests
- Python-dotenv
- Ngrok
What is Live Events:
Live Events are notifications sent by Canvas when specific actions happen, like accessing a page, submitting an assignment, or updating course settings. You can set up to receive these events through two methods: one using a queue system (AWS SQS) where messages are stored until retrieved, and another via direct internet notifications (HTTPS Webhook). These events are ideal for tracking activities in Canvas, useful for reporting, analytics, or enhancing services based on collected data. Here is a link to some example use cases of using Live Events: Live Events Examples
Setting Up Live Events:
Before getting started, ensure that the Data Services tab is enabled in your Canvas instance. If it is not, refer to this Community guide for setup instructions: How do I install Canvas Data Services using Live events in my account?
Course Completion Live Event:
We will be using the Course Completion live event endpoint. This event triggers when a student has completed all module requirements in their course. Verify that the course you will be using has these requirements set.
Setting Up Your Environment:
You will need to install the required Python packages using pip. Here is an example:
pip install Flask requests python-dotenv
Create a `.env` file in the same directory as your script and add your Canvas API key. The `.env` file should contain:
key=your_api_key_here
⚠️ Important Reminder: Ensure your Canvas API keys are securely stored and never shared publicly.
Example Script:
Here is the example script that will be run. Please remember that this script is not supported by Instructure.
import os
from flask import Flask, request, jsonify
import requests
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
app = Flask(__name__)
# Constants
COURSE_ID_TO_COMPLETE = "5660" # Set the course ID for the completed course
COURSE_ID_TO_ENROLL = "5658" # Set the course ID for the course to enroll in
HOSTNAME = "panda.instructure.com" # Set the hostname of your Canvas instance
@app.route('/webhook', methods=['POST'])
def webhook():
data = request.get_json()
if not data:
return jsonify({"error": "Invalid JSON"}), 400
print("Received webhook data:", data)
# Extract user_id and course_id
user_id = data.get('body', {}).get('user', {}).get('id')
course_id = data.get('body', {}).get('course', {}).get('id')
# Check the course_id and call the enroll_user function
if course_id == COURSE_ID_TO_COMPLETE:
enroll_user(user_id)
else:
print(f"Course ID {course_id} is not handled")
return jsonify({"message": "Webhook received"}), 200
# Enroll the user in the course
def enroll_user(user_id):
token = os.environ.get('key') # Ensure the key is set in the environment variable
headers = {
'Authorization': f'Bearer {token}'
}
url = f"https://{HOSTNAME}/api/v1/courses/{COURSE_ID_TO_ENROLL}/enrollments"
payload = {
"enrollment[user_id]": user_id,
"enrollment[type]": "StudentEnrollment",
"enrollment[enrollment_state]": "active"
}
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 200:
print("User enrolled successfully")
else:
print(f"Failed to enroll user, {response.status_code} - {response.text}")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=False)
Under "Constants," set those variables to the correct IDs and your instance’s hostname.
How the Script Works:
- Loading Environment Variables: The script uses `python-dotenv` to load environment variables from a `.env` file. This is where you store your Canvas API key.
- Flask Application: The Flask application listens for POST requests on the `/webhook` endpoint. When a request is received, it extracts the `user_id` and `course_id` from the JSON payload.
- User Enrollment: If the `course_id` matches the predefined `COURSE_ID_TO_COMPLETE`, the script calls the `enroll_user` function to enroll the user in the specified course using the Canvas API.
- API Call: The `enroll_user` function constructs the API request with the necessary headers and payload and sends a POST request to the Canvas API to enroll the user.
Running the Script:
To run the script, navigate to the directory in your terminal and execute it with Python:
python webhook.py
python webhook.py
The Flask application will start and listen for incoming webhook requests on port 8080.
Getting the Webhook URL for Canvas:
Now, use Ngrok to get a URL that Canvas can reach. Follow this getting started guide to set up Ngrok. Once you have it set up, go to your terminal and set up port forwarding to generate the URL you will use in Canvas. In your terminal, use:
ngrok http 8080
Running the code above will generate your forwarding address, which will look something like this: https://c8e1-35-141-46-187.ngrok-free.app
Integrating with Canvas:
Now that we have our Flask app running and our port forwarding set up, it’s time to add the final details to Canvas. Follow this guide to learn how to subscribe to Live Events: How do I subscribe to Live Events using Canvas Data Services?
Set up the subscription using HTTPS: Configure HTTPS Data Stream, setting the URL to the Ngrok URL you received and adding /webhook at the end also subscribing to the course > course completed, and check both user and system generated. Once your settings are in place, click Save.
Testing It Out!
Now that everything is in place, go to the course you have set up, act as a user to complete the requirements, and the live event should fire, enrolling the user in the next course you set in the script.
Recommendations for Scaling:
- For large-scale use, move to a queue system like AWS SQS to ensure all events are processed.
- Move the script to AWS Lambda to avoid local bottlenecks.
- If running locally, use a language that can handle concurrency easily, like GO. 😀
- Implement better error handling for edge cases.
Engage and Share:
How are you using Live Events to enhance your Canvas LMS workflows? Share your use cases or questions below!
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.