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
while
loop that checks ifrequest
exists. - Call successive pages using
list_next
method. This method can be used to retrieve successive pages, based on therequest
andresponse
from previous page. With this, you don't need to usepageToken
. - If a next page doesn't exist,
request
will 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
nextPageToken
from the response to the first request. - Start a
while
loop that checks ifnextPageToken
exists. - Inside the
while
loop request successive pages using thenextPageToken
retrieved in last response. - If there's no next page,
nextPageToken
will 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
users
list, using extend.
Post a Comment for "How Can I Get All Users On Google Admin_sdk?"