Automate user invites with this Python script. In this script, we utilize the Esper API to create invites from a CSV file.
This guide might work for you if:
- You have an understanding of APIs and Python.
- Have an Esper API key.
import csv
import json
import requests
def create_invite(email, role, enterprise_id, connection_id, groups, tenant_name, bearer_token):
invite_body = {
"email": email,
"meta": {
"email": email,
"profile": {
"role": role,
"enterprise": enterprise_id,
"groups": groups or [] # Default to empty list if groups is None
}
},
"connection_id": connection_id # if connection_id else None Ensure None is used for null
}
url = f"https://{tenant_name}-api.esper.cloud/api/authn2/v0/tenant/{enterprise_id}/invite"
headers = {'Authorization': f'Bearer {bearer_token}', 'Content-Type': 'application/json'}
# Send the POST request
response = requests.post(url, json=invite_body, headers=headers)
# Log the request and response details
print("Request URL:", url)
print("Request Payload:", invite_body)
print("Response Code:", response.status_code)
try:
print("Response Body:", response.json())
except json.JSONDecodeError:
print("Failed to decode JSON response:", response.text)
def process_csv(file_path, enterprise_id, tenant_name, bearer_token):
try:
with open(file_path, mode='r', encoding='utf-8') as csv_file:
csv_reader = csv.DictReader(csv_file)
# Normalize header names by stripping whitespace
csv_reader.fieldnames = [field.strip() for field in csv_reader.fieldnames]
for row in csv_reader:
email = row.get('email')
role = row.get('role')
groups = [group.strip() for group in row.get('groups', '').split(',')] if row.get(
'groups') else [] # Strip whitespace from groups
connection_id = row.get('connection_id').strip() if row.get(
'connection_id') else None # Ensure None for null
# Validate required fields
if not email or not role:
print(f"Skipping row due to missing required fields: {row}")
continue
# Call create_invite for each row
create_invite(email, role, enterprise_id, connection_id, groups, tenant_name, bearer_token)
except FileNotFoundError:
print(f"Error: File {file_path} not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
# Replace these values with your actual details
enterprise_id = 'enterprise id'
tenant_name = 'tenant name'
csv_file_path = 'path/to/csv'
bearer_token = 'API key'
process_csv(csv_file_path, enterprise_id, tenant_name, bearer_token)
Example CSV
email,role,groups,connection_id
andi@esper.io,Enterprise Admin,,5c0f7825-ca4c-46bc-bc41-8d63047d7462
cupcake@esper.io,Viewer,39b9c7d1-e36b-47b6-92e7-a17271954c50,
donut@esper.io,Enterprise Admin,,
eclair@esper.io,Enterprise Admin,,
icecream@esper.io,Group Viewer,"39b9c7d1-e36b-47b6-92e7-a17271954c50, 453fc2f9-a96a-4350-8b0a-40e8d3e96a6b",
Step Breakdown
Step 1 Create a CSV file.
Create a CSV file with the following headers:
Header | Description | Required? |
The user’s email address. | Required | |
role | The user’s role. Must be a default user role: Enterprise Admin, Viewer, Group Admin, or Group Viewer. | Required |
group | The group ID. The user will have access to these groups if defined. See how to find the group ID or use the List device groups API. For multiple groups, wrap groups in quotations (“). | Optional |
connection_id | The SSO connection ID if using SSO. Use the List connections API to find the connection’s ID. | Optional |
Step 2 Create the JSON request body
Create the request body.
invite_body = {
"email": email,
"meta": {
"email": email,
"profile": {
"role": role,
"enterprise": enterprise_id,
"groups": groups or [] # Default to empty list if groups is None
}
},
"connection_id": connection_id # if connection_id else None ensure None is used for null
}
Step 3 Create the POST request
We implement logs at this step to identify any errors during the request process.
url = f"https://{tenant_name}-api.esper.cloud/api/authn2/v0/tenant/{enterprise_id}/invite"
headers = {'Authorization': f'Bearer {bearer_token}', 'Content-Type': 'application/json'}
# Send the POST request
response = requests.post(url, json=invite_body, headers=headers)
# Log the request and response details
print("Request URL:", url)
print("Request Payload:", invite_body)
print("Response Code:", response.status_code)
try:
print("Response Body:", response.json())
except json.JSONDecodeError:
print("Failed to decode JSON response:", response.text)
Step 4 Read the CSV file
Clean the CSV data. The console will skip the row if the required data isn’t present.
try:
with open(file_path, mode='r', encoding='utf-8') as csv_file:
csv_reader = csv.DictReader(csv_file)
# Normalize header names by stripping whitespace
csv_reader.fieldnames = [field.strip() for field in csv_reader.fieldnames]
for row in csv_reader:
email = row.get('email')
role = row.get('role')
groups = [group.strip() for group in row.get('groups', '').split(',')] if row.get(
'groups') else [] # Strip whitespace from groups
connection_id = row.get('connection_id').strip() if row.get(
'connection_id') else None # Ensure None for null
# Validate required fields
if not email or not role:
print(f"Skipping row due to missing required fields: {row}")
continue
Step 5 Create a request for each invite
If present, any additional errors will be logged here.
# Call create_invite for each row
create_invite(email, role, enterprise_id, connection_id, groups, tenant_name, bearer_token)
except FileNotFoundError:
print(f"Error: File {file_path} not found.")
except Exception as e:
print(f"An error occurred: {e}")
Step 6 Define the variables and run the script
Ensure your API key is never published to a public directory.
# Example usage
# Replace these values with your actual details
enterprise_id = 'enterprise ID'
tenant_name = 'tenant name'
csv_file_path = 'path/to/csv'
bearer_token = 'API key'
process_csv(csv_file_path, enterprise_id, tenant_name, bearer_token)
Automate user invites with the Esper API.