Skip to end of banner
Go to start of banner

Code Example

Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

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 from environment variables. For local testing, you could even hardcode these on lines 7:8. 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.

Create test and assign candidates using the IA API
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']
api_base_url = "https://ias.inspera.no/api/"
api_auth_path = "authenticate/token/"
auth_params = {"code": auth_token, "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

"""Helper to grab a list of students from a local CSV file. 
   This could be data coming from your DB/integration platform. """
def get_student_list_from_csv(csv_file_name):
    students = []
    with open(csv_file_name, 'rb') 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

"""Helper that creates a test in IA with the given (external) id and name, 
   using the Inspera API with the given session token."""
def create_ia_test(token, test_name, test_id, start_time, end_time):
    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"]

"""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."""
def assign_candidates(token, test_id, candidates):
    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"})
    #uncomment to show raw JSON return value from the API 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).json()["access_token"]
    print "Will go on using token " + session_token
    ia_test_id = create_ia_test(session_token, "My API testing test", "externalTest1234", "2018-05-21T12:35:40Z", "2018-06-21T15:00:40Z")
    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


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 from environment variables. For local testing, you could even hardcode these on lines 9:10. 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.

Create test and assign candidates using the IA API
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']
api_base_url = "https://ias.inspera.no/api/"
api_auth_path = "authenticate/token/"
auth_params = {"code": auth_token, "client_id": client_id, "grant_type": "authorization_code"}
api_create_admin_path = "v1/users/admin/"

"""Helper to grab a list of test planners from a local CSV file. 
   This could be data coming from your DB/integration platform. """
def get_planner_list_from_csv(csv_file_name):
    admins = []
    with open(csv_file_name, 'rb') as csvfile:
        csvreader = csv.reader(csvfile, delimiter = ',')
        for a in csvreader:
            admin = {}
            admin["externalId"] = a[0]
            admin["externalSystem"] = a[1]
            admin["username"] = a[2]
            admin["firstName"] = a[3]
            admin["lastName"] = a[4]
            admin["email"] = a[5]
            admin["orgUnitName"] = a[6]
            admins.append(admin)
    return admins

"""Helper that creates a planner in IA with the given values, 
   using the Inspera API with the given session token."""
def create_ia_test_planner(token, planner):
    create_planner_params = planner
    planner["role"] = "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"})
    #uncomment to show raw JSON return value from the API print result.text
    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:	
    session_token = requests.post(api_base_url + api_auth_path, data = auth_params).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 "role" is set directly in the sample script to "plan", could easily have been added to the CSV file.


  • No labels