In order to automate google accounts for our students, I have used google admin-sdk and users:insert method
- https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/insert
- https://developers.google.com/admin-sdk/directory/v1/guides/manage-users
This is my code:
import json
from google.oauth2 import service_account
import googleapiclient.discovery
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']
SERVICE_ACCOUNT_FILE = 'credentials_admin_services.json'
#SERVICE_ACCOUNT_FILE = 'credentials_ctc_users.json'
DELEGATE='admin@crackthecode.pe' # Service account will impersonate this user. Must have proper admin privileges in G Suite.
TARGET='crackthecode.pe' # Service account wants to access data from this.
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
credentials_delegated = credentials.with_subject(DELEGATE)
service = googleapiclient.discovery.build('admin', 'directory_v1', credentials=credentials_delegated)
userInfo = {
"name": { # JSON template for name of a user in Directory API. # User's name
"givenName": "John", # First Name
"familyName": "Smith", # Last Name
},
"primaryEmail": "jsmith@crackthecode.la",
"password": "somepassword_",
}
response = service.users().insert(body=json.dumps(userInfo)).execute()
print(response)
This is the error I get:
googleapiclient.errors.HttpError:
HttpError 400 when requesting https://admin.googleapis.com/admin/directory/v1/users?alt=json
'Invalid Input: primary_user_email',
'domain': 'global',