Intro
This article demonstrates how to programmatically manage Google Workspace administration using Google Workspace Directory API
The Admin SDK Directory API allows enterprise domain administrators to view and manage their organization's users, groups, devices, and resources.
Prerequisites
To Develop on Google Workspace particularly using the Admin SDK API the following has to be set up:
- A Google Cloud Project Account
- Enable the Admin SDK API
- An IAM Service account is created, and the JSON key downloaded
- Google Workspace Super Admin Login
- Python 3 Installed
Implementation Steps
Step 1
Create a GCP Cloud Project and Enable the Admin SDK API Reference Article
Step 2
Create a service account from your Google Cloud console, IAM, and download the key. Reference article
Step 3
Login into Google Workspace as a Super Admin and set up Domain-wide delegation:
From your Google Workspace admin console → Security → Access and data control → API controls → Manage Domain-Wide Delegation → Add new.
- Add Client ID from the Service Account Key you downloaded earlier
- Add required OAuth Scopes, for user and group creation the following scopes are required:
- Click Authorize
Step 4
Run the following command to install Google API Client Library.
pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client
Step 5
Create a Python script to manage users. The sample script below creates a new user in Google Workspace.
from googleapiclient.discovery import build
from google.oauth2 import service_account
# Load the service account credentials
SERVICE_ACCOUNT_FILE = "./path/to/your/service/account/key.json"
SCOPES = ["https://www.googleapis.com/auth/admin.directory.user"]
# Authenticate and build the API client
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# Set up admin API client
admin_email = "super-admin-email@example.com"
delegated_credentials = credentials.with_subject(admin_email)
service = build("admin", "directory_v1", credentials=delegated_credentials)
user_info = {
"name": {
"givenName": "Test",
"familyName": "Doe"
},
"password": "SecurePass123!",
"primaryEmail": "testdoe@example.com"
}
# Create the user
service.users().insert(body=user_info).execute()
print("User Created Successfully!")
Step 6
Save and run the above script using the command below
python file_name.py
If everything is set up correctly, the user will be created successfully on the workspace admin console.
I hope you've found this article useful.
Top comments (0)