Import
Overview¶
Import group information using API.
Preparations¶
Please Create an API Key before performing API operations.
Request¶
Send CSV data and JSON parameters using the request format below.
| Setting column | Value |
|---|---|
| HTTP Method | POST |
| Content-Type | multipart/form-data |
| Character Code | UTF-8 |
| URL | http://{server name}/api/groups/import (※1) |
| Body | Refer to "Column to Specify for Body" below |
(*1) Please edit the {server name} part suit your environment as appropriate.
Column to Specify for Body¶
| Column name | Value |
|---|---|
| parameters | Specify the contents of the "API Parameters" below as a JSON format string |
| file | Binary data of the CSV file to be registered |
API Parameters¶
| Column name | e.g. | Notes |
|---|---|---|
| ApiVersion | 1.1 | API version |
| ApiKey | 3da0fa3a7R61faf821... | Acquired API key |
| Encoding | Shift-JIS | CSV file encoding. Specify "UTF-8" or "Shift-JIS" |
| ReplaceAllGroupMembers | true | Specify whether to "Delete Members before Importing." If true is specified, all members of groups that match the group ID in the CSV file will be deleted before importing. |
Execution Example Sample¶
PowerShell (version 6.0 or later) Sample¶
PowerShell¶
$uri = 'http://servername/api/groups/import'
$filePath = "./sample.csv"
$form = @{
parameters = ConvertTo-Json @{
ApiVersion = 1.1;
ApiKey = "4d84b4773a58bbc3c4...";
Encoding = "UTF-8";
};
file = Get-Item -Path $filePath;
}
Invoke-WebRequest -Uri $uri -Method Post -Form $form
Python Sample¶
Python¶
import requests
import json
url = "https://servername/api/groups/import"
filePath = "./sample.csv"
data = {
"parameters": json.dumps({
"ApiVersion" : 1.1,
"ApiKey" : "4d84b4773a58bbc3c4...",
"Encoding" : "UTF-8"
})
}
files = {
"file":("sample.csv", open(filePath,"rb"), "text/csv")
}
response = requests.post(url, data, files=files)
print(response.content.decode())
Response¶
The json data in the following format will be returned.
JSON¶
Code Samples¶
Modify 【 ... 】 in the code as necessary.¶
1. Read CSV files from an external system and import groups
This sample generates a CSV file for import
based on CSV files output from an external system, and imports it with the API.
Overview¶
It receives the user and organization information of an external system as CSV files,
and creates or updates groups with the Pleasanter Import Groups API.
The process flow is as follows.
- Read the input CSV files
- Get the existing groups from Pleasanter (/api/groups/get)
- Identify the existing groups by group name
- Generate the CSV file for the group import
- Run the Import Groups API (/api/groups/import)
Prerequisites¶
The users are already registered in Pleasanter
Group names are unique (used to decide whether to create or update)
Input Files¶
There are three input files, assumed to come from an external system.
groups.csv¶
A CSV file that defines the group information.
| Column name | Description |
|---|---|
| group_code | Group identification code |
| group_name | Group name |
| is_active | 1: Enabled / 0: Disabled |
| remark | Description |
Sample
group_code,group_name,is_active,remark
GRP_ADMIN,Administration Headquarters,1,Administration division
GRP_SALES,Sales Headquarters,1,Sales division
users.csv¶
A CSV file that defines the user information.
| Column name | Description |
|---|---|
| user_id | User identification ID |
| login_id | Pleasanter login ID |
| user_name | User name |
| Mail address | |
| is_active | 1: Enabled / 0: Disabled |
Sample
user_id,login_id,user_name,mail,is_active
0001,yamada.taro,Taro Yamada,yamada@example.co.jp,1
0002,sato.hanako,Hanako Sato,sato@example.co.jp,1
user_group_memberships.csv¶
A CSV file that defines which groups the users belong to.
| Column name | Description |
|---|---|
| user_id | User ID |
| group_code | Group code |
| is_active | 1: Enabled / 0: Disabled |
| is_group_admin | 1: Group administrator / 0: Regular member |
Sample
Output File¶
The following CSV file is generated.
The format of the CSV file follows the specifications of Group Management Function: Import/Export.
Python(api_group_import.py)¶
import csv
import json
from pathlib import Path
import requests
# ==============================
# Pleasanter connection settings
# ==============================
BASE_URL = "【URL】"
API_KEY = "【API key】"
API_VERSION = 1.1
ENCODING = "UTF-8"
# True : Generate the CSV file only
# False: Generate the CSV file and then run the import
DRY_RUN = True
# ==============================
# File settings (change them as appropriate for your environment)
# ==============================
INPUT_DIR = Path("./input")
OUTPUT_DIR = Path("./output")
GROUPS_CSV = INPUT_DIR / "groups.csv"
USERS_CSV = INPUT_DIR / "users.csv"
MEMBERSHIPS_CSV = INPUT_DIR / "user_group_memberships.csv"
GROUP_IMPORT_CSV = OUTPUT_DIR / "groups_import.csv"
# ==============================
# CSV input/output settings (change them as appropriate for your environment)
# ==============================
def read_csv(path):
with open(path, "r", encoding="utf-8-sig", newline="") as f:
return [
{k.strip(): (v or "").strip() for k, v in row.items()}
for row in csv.DictReader(f)
]
def write_csv(path, headers, rows):
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8-sig", newline="") as f:
writer = csv.DictWriter(f, fieldnames=headers)
writer.writeheader()
writer.writerows(rows)
def is_active(row):
return str(row.get("is_active", "1")) == "1"
def to_disabled(row):
return "0" if is_active(row) else "1"
def to_group_admin(row):
return "1" if str(row.get("is_group_admin", "0")) == "1" else "0"
# ==============================
# Pleasanter API operations
# ==============================
def post_json(url, payload):
r = requests.post(
url,
json=payload,
headers={"Content-Type": "application/json"},
)
r.raise_for_status()
return r.json()
# ==============================
# File upload operations
# ==============================
def post_file(url, params, file_path):
with open(file_path, "rb") as f:
files = {"file": (file_path.name, f, "text/csv")}
data = {"parameters": json.dumps(params)}
r = requests.post(url, data=data, files=files)
r.raise_for_status()
return r.json()
# ==============================
# Create a dictionary to check whether a group is already registered
# ==============================
def get_existing_groups():
data = post_json(
f"{BASE_URL}/api/groups/get", {"ApiVersion": API_VERSION, "ApiKey": API_KEY}
)
groups = {}
for row in data["Response"]["Data"]:
groups[row["GroupName"]] = row
return groups
# ==============================
# Create the row data for the CSV file
# ==============================
def build_rows(groups, users, memberships, existing_groups):
users_by_id = {u["user_id"]: u for u in users}
groups_by_code = {g["group_code"]: g for g in groups}
rows = []
# Rows for the groups themselves
for group in groups:
current = existing_groups.get(group["group_name"], {})
rows.append(
{
"グループID": str(current.get("GroupId", "")),
"グループ名": group["group_name"],
"説明": group.get("remark", ""),
"メンバー種別": "",
"メンバーキー": "",
"メンバー名": "",
"メンバーは管理者": "0",
"無効": to_disabled(group),
}
)
# Rows for the members
for membership in memberships:
if not is_active(membership):
continue
group = groups_by_code[membership["group_code"]]
user = users_by_id[membership["user_id"]]
current = existing_groups.get(group["group_name"], {})
rows.append(
{
"グループID": str(current.get("GroupId", "")),
"グループ名": group["group_name"],
"説明": group.get("remark", ""),
"メンバー種別": "User",
"メンバーキー": user["login_id"],
"メンバー名": user["user_name"],
"メンバーは管理者": to_group_admin(membership),
"無効": to_disabled(group),
}
)
return rows
# ==============================
# Run the group import
# ==============================
def import_groups(file_path):
return post_file(
f"{BASE_URL}/api/groups/import",
{
"ApiVersion": API_VERSION,
"ApiKey": API_KEY,
"Encoding": ENCODING,
"ReplaceAllGroupMembers": True,
},
file_path,
)
# ==============================
# Main process
# ==============================
def main():
groups = read_csv(GROUPS_CSV)
users = read_csv(USERS_CSV)
memberships = read_csv(MEMBERSHIPS_CSV)
existing_groups = get_existing_groups()
rows = build_rows(groups, users, memberships, existing_groups)
write_csv(
GROUP_IMPORT_CSV,
[
"グループID",
"グループ名",
"説明",
"メンバー種別",
"メンバーキー",
"メンバー名",
"メンバーは管理者",
"無効",
],
rows,
)
print("CSV generated:", GROUP_IMPORT_CSV)
if DRY_RUN:
print("The import is not run because DRY_RUN=True")
return
result = import_groups(GROUP_IMPORT_CSV)
print(json.dumps(result, indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()
Run¶
Execution Result¶
Confirmation Items in Case of Error¶
・Precautions when using the API and things to check if an error occurs
・FAQ: What to check if modified configuration files or API requests (JSON format) are not recognized correctly