Skip to content

Instantly share code, notes, and snippets.

@vishalsachdev
Last active April 4, 2025 01:07
Show Gist options
  • Select an option

  • Save vishalsachdev/2360fb2efdb37f29e953b295a85424e4 to your computer and use it in GitHub Desktop.

Select an option

Save vishalsachdev/2360fb2efdb37f29e953b295a85424e4 to your computer and use it in GitHub Desktop.
# This code helps you get a CSV roster of student names( Lastname, first name) along with their group names
# using the CANVAS api. Every user's API gives them access based on information they can see inside canvas
# The code below assumes CANVAS at Illinois, and requires two inputs: The API and the course_id
import requests
import json
import csv
# get a Canvas access token - https://canvas.illinois.edu/profile/settings --> Approved Integrations --> New Access token
# Enter with your access token from Canvas in the API-Key field below
# Base URL and API Key for Canvas at Illinois. If this is used at another university, change the base URL
API_URL = "https://canvas.illinois.edu/api/v1/"
API_KEY = "your canvas API key " # User should replace this with their own API key
# Headers used for API requests, mainly for authentication purposes
headers = {
'Authorization': f'Bearer {API_KEY}'
}
def paginated_get(url, headers):
results = []
while url:
r = requests.get(url, headers=headers)
r.raise_for_status()
# Append the results of the current page
results.extend(r.json())
# Check for pagination links in the headers
links = r.links
url = links['next']['url'] if 'next' in links else None
return results
def get_user(course_id, user_id):
"""Fetch user details for a specific user within a course."""
endpoint = f'courses/{course_id}/users/{user_id}'
url = API_URL + endpoint
r = requests.get(url, headers=headers)
r.raise_for_status() # Raises an error if the API request fails
return r.json()
def get_course_groups(course_id):
"""Retrieve all group details associated with a specific course."""
endpoint = f'courses/{course_id}/groups'
url = API_URL + endpoint
r = requests.get(url, headers=headers)
r.raise_for_status() # Raises an error if the API request fails
return r.json()
def get_group_users(group_id):
"""Fetch all users associated with a specific group."""
endpoint = f'groups/{group_id}/users'
url = API_URL + endpoint
r = requests.get(url, headers=headers)
r.raise_for_status() # Raises an error if the API request fails
return r.json()
def format_name(full_name):
"""Format a full name as 'Lastname, Firstname'."""
# Split the name into components
name_parts = full_name.split()
# Handle single name cases (e.g., "Madonna", "Cher")
if len(name_parts) == 1:
return name_parts[0]
# For names with more than one part, format as 'Lastname, Firstname'
last_name = name_parts[-1]
first_name = " ".join(name_parts[:-1])
return f"{last_name}, {first_name}"
def main():
"""Main execution function."""
course_id = 'replace with course_id' # User should replace this with the relevant course ID
# Fetch all groups within the course
groups = get_course_groups(course_id)
rows = [] # List to store formatted names and groups
for group in groups:
users = get_group_users(group['id'])
for user in users:
formatted_name = format_name(user['name'])
rows.append([formatted_name, group['name']])
# Write the data to a CSV file
with open('students_and_groups.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(["Student Name", "Group Name"]) # CSV header
writer.writerows(rows) # Write rows of student names and groups
if __name__ == "__main__":
main() # Execute the main function when the script is run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment