Code Example
Sample scenario using Python to create a test and assign candidates
Below is a Python snippet that creates a test and assigns a few students. It reads the client_id and authentication token as well as the API URL from environment variables. For local testing, you could even hardcode these on lines 7:10. The example reads the student info from a CSV file given as the only command line parameter to the script. This could naturally be replaced by data coming from a database, integration platform or similar - the use of CSV here is only for demo purposes (in fact, for CSV import you can simply use the normal user interface in Inspera Assessment to import the candidates). The example shows how to set extra time per candidate, as well as specifying the building and room for each candidate.
It should be noted that the IA API also supports posting the candidates along with the test creation, but for the sake of demonstrating the APIs, two calls (in addition to the session token generation step) were used in the below example. The http request details are done through the wonderful requests library.
import requests import os import csv import sys # this has to be manually replaced by a valid auth token and client id, if env vars not set auth_token = os.environ['IA_ACCESS_TOKEN'] client_id = os.environ['IA_CLIENT_ID'] # this typically has the form https://<CLIENT>.inspera.no/api/ api_base_url = os.environ['IA_API_URL'] api_auth_path = "authenticate/token/" auth_params = {"client_id": client_id, "grant_type": "authorization_code"} api_create_test_path = "v1/test" api_assign_candidates_path = "v1/test/%d/candidates" # %d to be replaced by testId before using the URL, sprintf-style # this will be the external id of the test created ext_test_id = "externalTest123456789" # this will be the name of the test created test_name = "UNSW API testing test updated"; def get_student_list_from_csv(csv_file_name): """Helper to grab a list of students from a local CSV file. This could be data coming from your DB/integration platform. """ students = [] with open(csv_file_name, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter = ',') for s in csvreader: student = {} student["candidateId"] = s[0] student["buildingName"] = s[1] student["roomName"] = s[2] student["externalId"] = s[3] student["extraTimeMinutes"] = s[4] students.append(student) return students def create_ia_test(token, test_name, test_id, start_time, end_time): """Helper that creates a test in IA with the given (external) id and name, using the Inspera API with the given session token.""" create_test_params = { "externalTestId": test_id, "title": test_name, "startTime": start_time, "endTime": end_time } result = requests.post(api_base_url + api_create_test_path, json=create_test_params, headers={"Authorization": "bearer " + token, "Content-type": "application/json"}) #print result.text return result.json()["assessmentRunId"] def assign_candidates(token, test_id, candidates): """Helper that assignes the given list of candidates to a test in IA given the IA id of the test, using the Inspera API with the given session token.""" assign_candidate_params = {"testId": test_id, "candidates" : candidates} assign_candiates_url = api_base_url + (api_assign_candidates_path % test_id) result = requests.post(assign_candiates_url, json=assign_candidate_params, headers={"Authorization": "bearer " + token, "Content-type": "application/json"}) print(result.text) print("Creating a test in IA and populating some students from CSV...") if not len(sys.argv) == 2: print("Please provide the CSV file name as the only script parameter") else: session_token = requests.post(api_base_url + api_auth_path, data = auth_params, headers={"code": auth_token}).json()["access_token"] print("Will go on using token " + session_token) ia_test_id = create_ia_test(session_token, test_name, ext_test_id, "2018-05-25T12:30:00Z", "2018-05-25T17:30:00Z") print("Will assign students to test " + str(ia_test_id)) students = get_student_list_from_csv(sys.argv[1]) assign_candidates(session_token, ia_test_id, students) print("Assigned " + str(len(students)) + " candidates to test " + str(ia_test_id))
The CSV file used in this sample was:
12345,Building 1,Room 101,extId12345,0 12346,Building 1,Room 101,extId12346,30
(The above sample was updated to Python 3.8 on May 29th 2020, if you for any reason would like the Python 2.7 version, reach out to your contact.)
Sample scenario using Python to create two test planners (admins)
Below is a Python snippet that creates two test plannners, using the users API. It reads the client_id and authentication token as well as root API URL from environment variables. For local testing, you could even hardcode these on lines 9:12. The example reads the planner info from a CSV file given as the only command line parameter to the script. This could naturally be replaced by data coming from a database, integration platform or similar - the use of CSV here is only for demo purposes. The example shows how to set the organization unit, such as the school, of each user - which in terms can be used for setting role-based permissions in IA.
import requests import os import csv import sys # this example creates a few test planners from a CSV file given as a parameter to the script # this has to be manually replaced by a valid auth token and client id, if env vars not set auth_token = os.environ['IA_ACCESS_TOKEN'] client_id = os.environ['IA_CLIENT_ID'] # this typically has the form https://<CLIENT>.inspera.no/api/ api_base_url = os.environ['IA_API_URL'] api_auth_path = "authenticate/token/" auth_params = {"client_id": client_id, "grant_type": "authorization_code"} api_create_admin_path = "v1/users/admin/" def get_planner_list_from_csv(csv_file_name): """Helper to grab a list of test planners from a local CSV file. This could be data coming from your DB/integration platform. """ admins = [] with open(csv_file_name, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') for a in csvreader: admin = {} admin["externalId"] = a[0] admin["authType"] = a[1] admin["username"] = a[2] admin["firstName"] = a[3] admin["lastName"] = a[4] admin["email"] = a[5] admin["orgUnitMemberships"] = a[6] admins.append(admin) return admins def create_ia_test_planner(token, planner): """Helper that creates a planner in IA with the given values, using the Inspera API with the given session token.""" create_planner_params = planner # roles is now an array replacing the old "role" planner["roles"] = ["plan"]; # "evaluate", "plan", "author" supported, could also come from ext system, but hardcoded for demo result = requests.post(api_base_url + api_create_admin_path, json=create_planner_params, headers={"Authorization": "bearer " + token, "Content-type": "application/json"}) print(result.text) print(result.request.body) return result.json()["userId"] print("Creating test planners in IA from CSV...") if not len(sys.argv) == 2: print("Please provide the CSV file name as the only script parameter") else: response = requests.post(api_base_url + api_auth_path, data=auth_params, headers={"code": auth_token}) print(response.text) session_token = response.json()["access_token"] print("Will go on using token " + session_token) planners = get_planner_list_from_csv(sys.argv[1]) ia_planner_ids = [] for planner in planners: print("Will create planner " + str(planner["firstName"]) + " " + str(planner["lastName"])) ia_planner_ids.append(create_ia_test_planner(session_token, planner)) print("Created " + str(len(planners)) + " in IA, userIds in IA: " + str(ia_planner_ids))
The CSV file used in this sample was:
1234566,MSADFS,pp1,Peter,Planner,peter.planner@test.com,School of wining and dining 1234567,MSADFS,pp2,Peter,Pan,peter.pan@test.com,School of wining and dining
The format here is in order externalId, externalSystem, username, firstName, lastName, email, orgUnitName - the additional field "roles" (now an array, changed this this example was originally created) is set directly in the sample script to "plan", could easily have been added to the CSV file.