Python API Post request 404 error

Jump to solution
bertscjn
Community Member

Hey. I'm trying to loop through a csv file to enroll students into a course but I keep getting a 404 error. Can anyone give me some advice as to why? When I switch the request method to GET from POST I get a 200 status code. I've been staring at this for a while now so maybe I'm over looking something? 

Column Headers from the CSV file: 
recordcourse_iduser_idrolestatus
 
___________________________________________________________ 
 
import numpy as np
import pandas as pd
import requests
import json
 
dataset = pd.read_csv("PATH_TO_CSV_FILE")
df = pd.DataFrame.from_records(dataset)
ndarray = df.to_numpy()
 
secret_token = [MY API KEY]
headers = {'Authorization' : 'Bearer ' + secret_token}
courseID = [MY COURSE ID NUMER]
url = "https://[MY INSTITUTION].instructure.com/api/v1/courses/" + str(courseID) + "/enrollments"
course = ""
for x in ndarray:
    course = x[2]
    print(course)
    payload = {'enrollment[user_id]': course, 'enrollment[course_section_id]' : courseID}
    r = requests.post(url,headers = headers, params = payload)
    print(r.status_code)
Labels (5)
0 Likes
1 Solution
bertscjn1
Community Explorer

Thanks everyone for their help. I was able to get it solved, and am posting my updated code for anyone that may have the same issue in the future. Turns out it was the "enrollment[course_section_id] " parameter that was throwing the error. According to the API documentation, this parameter is skipped over if the section ID is in the URL being passed. Since it is in my instance, then I could remove it. By removing it, I was successfully able to make the API call to bulk enroll users with specific roles in the course! 

 

import requests
import json
import csv
 
csv_filename = '[PATH TO MY CSV FILE]'
with open(csv_filename) as f:
reader = csv.reader(f)
lst = list(reader)
 
secret_token = [MY API KEY]
headers = {'Authorization' : 'Bearer ' + secret_token}
courseID = [MY COURSE ID NUMER]
url = "https://[MY INSTITUTION].instructure.com/api/v1/courses/" + str(courseID) + "/enrollments"
 
for x in ndarray:
userID = x[2]
enrollmentType = x[3]
print(userID)
payload = {'enrollment[user_id]': userID, 'enrollment[type]': enrollmentType}
r = requests.post(url,headers = headers, data = payload)
print(r.status_code)

View solution in original post