pythongoogle-apigoogle-admin-sdkgoogle-api-python-client

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 Quickstart example) How could I list all my 1000 users? I've already read about Nextpagetoken, but I don't know how I can get or implement it. Somebody could help me please?

from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']

def main():
    """Shows basic usage of the Admin SDK Directory API.
    Prints the emails and names of the first 10 users in the domain.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

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

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

    if not users:
        print('No users in the domain.')
    else:
        print('Users:')
        for user in users:
            print(u'{0} ({1})'.format(user['primaryEmail'],
                user['name']['fullName']))


if __name__ == '__main__':
    main()

Solution

  • 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:

    def list_users(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', []))
        if not users:
            print('No users in the domain.')
        else:
            for user in users:
                print('{0} ({1})'.format(user['primaryEmail'],user['name']['fullName']))
    

    Method 2. pageToken:

    def list_users(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', []))
        if not users:
            print('No users in the domain.')
        else:
            for user in users:
                print('{0} ({1})'.format(user['primaryEmail'],user['name']['fullName']))
    

    Note:

    Reference: