Automate admin report 'Grade Export'

morris_gart
Community Explorer

I have a need to automate this admin report on a nightly basis but cannot seem to get the python script correct.  I have the access token but I get a 403 denied error for 

endpoint = f'{BASE_URL}/courses/{course_id}/students/submissions'

This is the current version of the script:

import requests
import csv
import datetime

# Replace with your Canvas API token and base URL
API_TOKEN = 'your_api_token'
BASE_URL = 'https://your_canvas_instance/api/v1'

# Headers for authentication
headers = {
'Authorization': f'Bearer {API_TOKEN}'
}

# Function to fetch courses for a specific term
def fetch_courses(term_id):
endpoint = f'{BASE_URL}/courses?enrollment_term_id={term_id}&enrollment_state=active'
response = requests.get(endpoint, headers=headers)
response.raise_for_status()
return response.json()

# Function to fetch data for a specific course
def fetch_data(course_id):
endpoint = f'{BASE_URL}/courses/{course_id}/students/submissions'
response = requests.get(endpoint, headers=headers)
if response.status_code == 403:
print(f"Access denied for course ID {course_id}. Check your API token permissions.")
return None
response.raise_for_status()
return response.json()

# Function to save data to CSV
def save_to_csv(data, course_id):
if data is None:
return
filename = f'grade_export_{course_id}_{datetime.datetime.now().strftime("%Y_%m_%d")}.csv'
with open(filename, mode='w', newline='') as file:
writer = csv.writer(file)
# Write headers
writer.writerow(['student name', 'student id', 'student sis', 'course', 'course id', 'course sis', 'section', 'section id', 'section sis', 'term', 'term id', 'term sis', 'current score', 'final score', 'enrollment state', 'unposted current score', 'unposted final score', 'current grade', 'final grade', 'unposted current grade', 'unposted final grade'])
# Write data rows
for item in data:
writer.writerow([item['student_name'], item['student_id'], item['student_sis'], item['course'], item['course_id'], item['course_sis'], item['section'], item['section_id'], item['section_sis'], item['term'], item['term_id'], item['term_sis'], item['current_score'], item['final_score'], item['enrollment_state'], item['unposted_current_score'], item['unposted_final_score'], item['current_grade'], item['final_grade'], item['unposted_current_grade'], item['unposted_final_grade']])

# Main function
def main():
term_id = 'your_term_id' # Canvas TermID
courses = fetch_courses(term_id)
for course in courses:
course_id = course['id']
data = fetch_data(course_id)
save_to_csv(data, course_id)

if __name__ == '__main__':
main()

Any assistance or maybe I am going about this all wrong?

Labels (1)
0 Likes