Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save salrashid123/de891486b5b595f561cbcdcdcb2c7b4a to your computer and use it in GitHub Desktop.
Save salrashid123/de891486b5b595f561cbcdcdcb2c7b4a to your computer and use it in GitHub Desktop.
List users with Google Directory API
#!/usr/bin/python
from apiclient.discovery import build
import httplib2
from oauth2client.service_account import ServiceAccountCredentials
from oauth2client.client import GoogleCredentials
import logging
import json
import sys
from apiclient import discovery
from apiclient import errors
import oauth2client
from oauth2client import client
from oauth2client import tools
from oauth2client.client import flow_from_clientsecrets
scope = 'https://www.googleapis.com/auth/admin.directory.user'
# A. with service accounts
#credentials = ServiceAccountCredentials.from_p12_keyfile('adminapi@fabled-ray-104117.iam.gserviceaccount.com',
# 'project1-5fc7d442817b.p12',
# scopes=scope)
#credentials = credentials.create_delegated('admin@demoapp2.com')
# B. with client_secrets and login as domain admin
flow = flow_from_clientsecrets('client_secret.json',
scope=scope,
redirect_uri='urn:ietf:wg:oauth:2.0:oob')
auth_uri = flow.step1_get_authorize_url()
print 'goto the following url ' + auth_uri
code = raw_input('Enter token:')
credentials = flow.step2_exchange(code)
http = httplib2.Http()
http = credentials.authorize(http)
data = ''
service = discovery.build('admin', 'directory_v1', http=http)
page_token = None
while True:
try:
results = service.users().list(customer='C023zw3ee', domain='demoapp2.com', pageToken=page_token).execute()
users = results.get('users', [])
print json.dumps(users, sort_keys=True, indent=4)
for u in users:
print json.dumps(u['primaryEmail'], sort_keys=True, indent=4)
page_token = results.get('nextPageToken')
if not page_token:
break
except errors.HttpError, error:
print 'An error occurred: %s' % error
break
@jgagan-crest
Copy link

Is a domain and customer field are required parameters in all the scenarios of directory API??

@salrashid123
Copy link
Author

you can use either https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/list

Either the customer or the domain parameter must be provided.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment