Reflecting Hires and Transfers via the System Settings REST API

Suppose that in conjunction with new hires in April, you need to register 30 Users, and as part of April transfers, you need to reassign affiliations for 50 Users. In this article, we will explain how to reflect these two tasks via REST API based on a CSV exported from an HR system.

Registering Users can also be done via [Bulk User Registration] under [System Settings] > [User List]. For a one-time operation, that approach is simpler. The procedure is explained in “Bulk Registering Users”.

Using the REST API is suitable when this task is repeated annually or monthly. By setting it up so that exports from your HR system can be fed directly into the script, subsequent runs require only replacing the CSV file and executing the process.

In this article, we assume that Organizations themselves (such as establishing or renaming departments/sections) remain unchanged. Additionally, we distinguish terms by calling names on the HR system side “Department Names” and those on the workflow infrastructure side “Organizations”.

The code example is written in Python 3, using the Requests package to send HTTP requests. The code is explained section by section and assembled into a single script under “Full Code” at the end.

Preparing the CSV File

Combine both new Users and transferring Users into a single CSV. Export from your HR system in the following format and save it as april.csv.

name,email,locale,timezone,qgroup1,qgroup2
Taro Tanaka,taro.tanaka@example.com,,,Sales Department,
Hanako Suzuki,hanako.suzuki@example.com,en,America/Los_Angeles,Development Department,Quality Assurance Office

name is the User Name, and email is the Email Address. Newly hired personnel are registered using these details, while existing Users have their affiliations updated to Organizations matching the listed Department Names.

Columns are divided into two types: those matching API parameter names and those for Department Names. name, email, locale, and timezone correspond directly to API parameter names. Aligning column names allows a dictionary loaded from a single CSV row to be passed directly to API calls. qgroup1 and qgroup2 are Department Name columns and do not exist as API parameters; these are converted into Organization IDs within the code before use. Because the remaining row dictionary is passed directly to API calls, if your HR system export contains additional columns such as employee IDs, filter the export to include only these 6 columns.

Arrange Department Name columns according to the number of concurrent positions. The leading column, qgroup1, serves as the Primary Organization affiliation. In the example above, Hanako Suzuki concurrently holds positions in both the Development Department and Quality Assurance Office, with the Development Department acting as her Primary Organization affiliation. This column arrangement matches the layout used during web UI bulk registration CSV imports. For Users without concurrent positions, the second column may remain blank.

If locale and timezone are left blank, system defaults are applied. Populate values only for rows requiring individual overrides, such as overseas personnel. Because these two columns apply strictly during User registration, including them in rows for existing Users will not alter their current settings.

Valid values for locale are ja, en, ko, zh_TW, and zh_CN. Valid values for timezone are regional timezone IDs (such as Asia/Tokyo) matching choices listed under [Account Settings] > [Timezone].

Preparing for API Calls

The executing User requires User Manager authorization and permission for API access via Basic authentication. Open the target User under [System Settings] > [User List] to verify that User Management privileges are assigned. Next, click [Edit] on the [API access via Basic Authentication] row and check “Permitted”. The password used for authentication is the string displayed under the [API Password] tab in [Account Settings] > [Password], which is distinct from the web login password.

Allowing API Access via Basic Authentication

Configure the connection target and credentials as follows:

import csv
import requests
from requests.auth import HTTPBasicAuth

BASE = 'https://example.questetra.net'
AUTH = HTTPBasicAuth('admin@example.com', '{API Password}')

All API calls are routed through the following helper function. Upon failure, it outputs the response body before stopping. The response body contains the errorCode alongside details indicating which parameter (param) received which input value (input). A comprehensive error code reference is available in “R3175: Response Error List (Workflow Infrastructure API)”.

def check(r):
    if not r.ok:
        print(r.status_code, r.text)
        r.raise_for_status()
    return r


def call(method, path, **kwargs):
    return check(requests.request(method, f'{BASE}{path}', auth=AUTH, **kwargs))

Parameter lists and response formats can be inspected via Swagger, accessible through [REST API Reference] in the left sidebar menu of the workflow infrastructure. Usage details are covered in “Trying Questetra REST API with Swagger”.

Retrieving the Organization List

For both User registration and affiliation updates, the API requires Organization IDs. Because the CSV contains Department Names, retrieve the list of Organizations first to build a dictionary mapping Organization Names to Organization IDs. All subsequent operations resolve Organization IDs through this dictionary.

The API listing Organizations imposes a maximum limit on records returned per call. Specify the count per request using limit and offset calls using start, looping until the returned record count falls below limit.

LIMIT = 10
groups = {}
start = 0
while True:
    r = call('GET', '/API/User/Qgroup/list',
             params={'start': start, 'limit': LIMIT})
    qgroups = r.json()['qgroups']
    groups.update({g['name']: g['id'] for g in qgroups})
    if len(qgroups) < LIMIT:
        break
    start += LIMIT

You can specify up to 1000 for limit. In this example, it is set to 10 to demonstrate looping behavior. Even if it is set to 1000, retain the looping structure to accommodate environments where Organization counts exceed that threshold.

Transfers: Reassigning Affiliations

The API for configuring User affiliations is /API/UGA/Quser/setMembership. The User’s affiliations are completely replaced by the payload specified in memberships. Specifying only new destination affiliations removes prior affiliations. We define this logic inside a dedicated function:

def move_user(quser_id, memberships):
    call('POST', '/API/UGA/Quser/setMembership',
         json={'quserId': quser_id, 'memberships': memberships})

In memberships, list affiliated Organizations individually and append primary to the Primary Organization. For example, setting Development Department (ID 12) as primary while concurrently assigning Quality Assurance Office (ID 34) uses [{'qgroupId': 12, 'primary': True}, {'qgroupId': 34}]. Specify primary on exactly one entry. Formatting CSV Department Names into this structure is detailed under “Row-by-Row Preprocessing and Routing”.

Transfers do not modify User Names. Because this function updates affiliations exclusively, the CSV name column is referenced only during registration. To update User Names (e.g., due to name changes), pass id and name to /API/UGA/Quser/update.

New Hires: User Registration

The API for adding Users is /API/UGA/Quser/add. The passed row payload represents a CSV row with Department Name columns removed and empty columns pruned. This preprocessing occurs in “Row-by-Row Preprocessing and Routing”.

def add_user(row, memberships):
    if len(memberships) == 1:
        row['primaryQgroupId'] = memberships[0]['qgroupId']
        call('POST', '/API/UGA/Quser/add', data=row)
        return
    r = call('POST', '/API/UGA/Quser/add', data=row)
    move_user(r.json()['quser']['id'], memberships)

If there are no concurrent positions, affiliation is established at the time of registration. Passing an Organization ID in add‘s primaryQgroupId configures the Primary Organization. For Users with concurrent positions, because primaryQgroupId accepts only a single Organization ID, the script calls move_user from the previous section immediately after User creation.

Do not specify passwords. Omitting password creates User accounts without pre-configured passwords. Individual Users set up their passwords personally via the “Forgot your password?” link on the web login page. This workflow matches web UI bulk registration behavior and is described in “Bulk Registering Users”.

Row-by-Row Preprocessing and Routing

Read the CSV row by row, converting Department Names to Organization IDs before searching for Users by Email Address. If a User is found, call move_user; otherwise, call add_user.

with open('april.csv', encoding='utf-8') as f:
    for row in csv.DictReader(f):
        names = [row.pop(k) for k in list(row) if k.startswith('qgroup')]
        names = [n for n in names if n]
        row = {k: v for k, v in row.items() if v}

        if not names:
            print(row.get('email'), 'Department Name is empty')
            continue
        missing = [n for n in names if n not in groups]
        if missing:
            print(row.get('email'), 'Department Name not found in Organization list:', missing)
            continue

        memberships = [{'qgroupId': groups[n]} for n in names]
        memberships[0]['primary'] = True

        found = requests.get(f'{BASE}/API/User/Quser/find', auth=AUTH,
                             params={'email': row['email']})
        if found.status_code != 400:
            check(found)
        if found.ok:
            move_user(found.json()['quser']['id'], memberships)
            print(row['email'], 'Updated affiliation')
        else:
            add_user(row, memberships)
            print(row['email'], 'Registered user')

Prune empty columns rather than passing them to API calls. Extracting Department Name columns from row leaves only API parameters in row. Passing empty strings explicitly overrides default values, causing validation errors for parameters such as locale or timezone.

Rows with all Department Name columns empty or containing Department Names absent from the Organization list print the Email Address and skip to the next row. Calling move_user with empty affiliations removes all existing Organization memberships for that User. Rows containing Department Names absent from the Organization list indicate naming discrepancies between the HR system and workflow infrastructure; notation mismatches are surfaced at this step.

memberships maps Department Names to Organization IDs. Because qgroup1 occupies the leading position in the CSV, the department corresponding to qgroup1 becomes the Primary Organization affiliation.

find returns HTTP 400 for unregistered Email Addresses. Treat 400 strictly as “not found”, while allowing other errors (such as authentication failures) to halt execution via check. This is why calls to find bypass call wrapper invocation.

If execution fails mid-process, re-run the CSV from the beginning safely. Because routing depends on Email Address lookups, already registered rows simply re-apply affiliation settings without creating duplicate User accounts.

Full Code

The complete code combining all preceding sections is shown below. Read “Execution Guidelines” before running the script.

import csv
import requests
from requests.auth import HTTPBasicAuth

BASE = 'https://example.questetra.net'
AUTH = HTTPBasicAuth('admin@example.com', '{API Password}')
LIMIT = 10


def check(r):
    if not r.ok:
        print(r.status_code, r.text)
        r.raise_for_status()
    return r


def call(method, path, **kwargs):
    return check(requests.request(method, f'{BASE}{path}', auth=AUTH, **kwargs))


def move_user(quser_id, memberships):
    call('POST', '/API/UGA/Quser/setMembership',
         json={'quserId': quser_id, 'memberships': memberships})


def add_user(row, memberships):
    if len(memberships) == 1:
        row['primaryQgroupId'] = memberships[0]['qgroupId']
        call('POST', '/API/UGA/Quser/add', data=row)
        return
    r = call('POST', '/API/UGA/Quser/add', data=row)
    move_user(r.json()['quser']['id'], memberships)


groups = {}
start = 0
while True:
    r = call('GET', '/API/User/Qgroup/list',
             params={'start': start, 'limit': LIMIT})
    qgroups = r.json()['qgroups']
    groups.update({g['name']: g['id'] for g in qgroups})
    if len(qgroups) < LIMIT:
        break
    start += LIMIT

with open('april.csv', encoding='utf-8') as f:
    for row in csv.DictReader(f):
        names = [row.pop(k) for k in list(row) if k.startswith('qgroup')]
        names = [n for n in names if n]
        row = {k: v for k, v in row.items() if v}
        if not names:
            print(row.get('email'), 'Department Name is empty')
            continue
        missing = [n for n in names if n not in groups]
        if missing:
            print(row.get('email'), 'Department Name not found in Organization list:', missing)
            continue
        memberships = [{'qgroupId': groups[n]} for n in names]
        memberships[0]['primary'] = True

        found = requests.get(f'{BASE}/API/User/Quser/find', auth=AUTH,
                             params={'email': row['email']})
        if found.status_code != 400:
            check(found)
        if found.ok:
            move_user(found.json()['quser']['id'], memberships)
            print(row['email'], 'Updated affiliation')
        else:
            add_user(row, memberships)
            print(row['email'], 'Registered user')

Execution Guidelines

First, execute using a single-row CSV and inspect [System Settings] > [User List] to confirm that User Name, Email Address, and Organization affiliations match expectations. POST APIs modify live workflow infrastructure data immediately upon invocation. Testing single rows for new hires and transfers individually validates routing logic. Once verified, process remaining CSV rows.

Decide the schedule for inviting new Users to set up passwords. Because accounts become active upon creation, when registering ahead of official start dates, send setup notifications timed to match start dates.

Related Pages