Search code examples
pythonflaskgoogle-cloud-platformgoogle-oauthapi-key

access user profile information in a google domain with python


Objective: my python web app access a google user's information from a customer. They already provided authorization to service account to access the scope of admin.directory.user.readonly and Im using this service account JSON file as credential to my app. credential_path = os.path.join(os.path.dirname(app.instance_path), 'cre.json') os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path

SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']
PATH_TO_CREDENTIALS = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')
GET_CREDENTIALS = PATH_TO_CREDENTIALS
PASS_CREDENTIALS = service_account.Credentials.from_service_account_file(GET_CREDENTIALS, scopes=SCOPES)

service = build('admin', 'directory_v1', credentials=PASS_CREDENTIALS)

# Call the Admin SDK Directory API
print('Getting the first 10 users in the domain')
results = service.users().list(customer='customer.com', domain='customer.com', maxResults=10, orderBy='email').execute()
users = results.get('users', [])

for user in users:
    print(u'{0} ({1})'.format(user['primaryEmail'], user['name']['fullName']))

Im getting:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://admin.googleapis.com/admin/directory/v1/users?customer=nidec-ga.com&domain=nidec-ga.com&maxResults=10&orderBy=email&alt=json returned "Bad Request". Details: "Bad Request">

Any idea what could be wrong?


Solution

  • You can't use domain and customer on the same GET request. In the Admin Google API documentation, it states the following for the domain field:

    • The domain name. Use this field to get fields from only one domain. To return all domains for a customer account, use the customer query parameter instead. Either the customer or the domain parameter must be provided.