How Can I Get All Users On Google Admin_sdk?
I need to list all users in my domain, but I can't because my domain there are more then 500 users and the default limit per page is 500. In this example below (the google Quickst
Solution 1:
You have to request the different pages iteratively. You can use a while loop for this.
There are two different ways to do this.
Method 1. list_next:
- Request the first page.
- Start a
whileloop that checks ifrequestexists. - Call successive pages using
list_nextmethod. This method can be used to retrieve successive pages, based on therequestandresponsefrom previous page. With this, you don't need to usepageToken. - If a next page doesn't exist,
requestwill returnNone, so the loop will end.
deflistUsers(service):
request = service.users().list(customer='my_customer', maxResults=500, orderBy='email')
response = request.execute()
users = response.get('users', [])
while request:
request = service.users().list_next(previous_request=request, previous_response=response)
if request:
response = request.execute()
users.extend(response.get('users', []))
ifnot users:
print('No users in the domain.')
else:
for user in users:
print(u'{0} ({1})'.format(user['primaryEmail'],user['name']['fullName']))
Method 2. pageToken:
- Request the first page (without using the parameter
pageToken). - Retrieve the property
nextPageTokenfrom the response to the first request. - Start a
whileloop that checks ifnextPageTokenexists. - Inside the
whileloop request successive pages using thenextPageTokenretrieved in last response. - If there's no next page,
nextPageTokenwill not be populated, so the loop will end.
deflistUsers(service):
response = service.users().list(customer='my_customer', maxResults=500, orderBy='email').execute()
users = response.get('users', [])
nextPageToken = response.get('nextPageToken', "")
while nextPageToken:
response = service.users().list(customer='my_customer', maxResults=500, orderBy='email', pageToken=nextPageToken).execute()
nextPageToken = response.get('nextPageToken', "")
users.extend(response.get('users', []))
ifnot users:
print('No users in the domain.')
else:
for user in users:
print(u'{0} ({1})'.format(user['primaryEmail'],user['name']['fullName']))
Note:
- In both methods, users from current iteration are added to the main
userslist, using extend.
Post a Comment for "How Can I Get All Users On Google Admin_sdk?"