0

In order to automate google accounts for our students, I have used google admin-sdk and users:insert method

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',
fcedillo
  • 48
  • 3
  • 10

1 Answers1

1

After further reviewing your code, the error lies here:

.insert(body=json.dumps(userInfo)

That is basically converting a Python object into a JSON string, where you can easily just enter it as a Python object.

Here is the modified 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=userInfo).execute()

print(response)

After testing this, my user was created successfully.

Yancy Godoy
  • 582
  • 2
  • 13