Hey there, fellow developer! Ready to dive into the world of Google Workspace Admin API integration? Let's roll up our sleeves and get coding with Python. We'll be using the google-api-python-client
package, so buckle up for a smooth ride.
Before we jump in, make sure you've got these bases covered:
First things first, let's get our tools in order. Fire up your terminal and run:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
Now, let's get you authenticated and ready to roll:
from google.oauth2 import service_account from googleapiclient.discovery import build SCOPES = ['https://www.googleapis.com/auth/admin.directory.user'] SERVICE_ACCOUNT_FILE = 'path/to/your/service_account.json' credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) delegated_credentials = credentials.with_subject('[email protected]') service = build('admin', 'directory_v1', credentials=delegated_credentials)
Let's start with something simple, like listing users:
results = service.users().list(customer='my_customer', maxResults=10).execute() users = results.get('users', []) for user in users: print(f"Name: {user['name']['fullName']}, Email: {user['primaryEmail']}")
Now that you've got the hang of it, let's try some more operations:
user = { 'primaryEmail': '[email protected]', 'name': { 'givenName': 'New', 'familyName': 'User' }, 'password': 'securepassword123' } service.users().insert(body=user).execute()
user_update = { 'name': { 'givenName': 'Updated', 'familyName': 'User' } } service.users().update(userKey='[email protected]', body=user_update).execute()
service.users().delete(userKey='[email protected]').execute()
When dealing with large result sets, pagination is your friend:
def get_all_users(service): users = [] page_token = None while True: results = service.users().list(customer='my_customer', pageToken=page_token).execute() users.extend(results.get('users', [])) page_token = results.get('nextPageToken') if not page_token: break return users
Let's add some robustness to our code:
from googleapiclient.errors import HttpError from time import sleep def api_call_with_retry(func, max_retries=5): for attempt in range(max_retries): try: return func() except HttpError as e: if e.resp.status in [429, 500, 503]: sleep(2 ** attempt) else: raise raise Exception(f"API call failed after {max_retries} retries")
And there you have it! You're now equipped to build powerful integrations with the Google Workspace Admin API. Remember, this is just the tip of the iceberg. There's so much more you can do, like working with groups, organizational units, and even setting up webhooks for real-time updates.
Keep exploring, keep coding, and most importantly, have fun! If you need more info, the Google Workspace Admin SDK documentation is your best friend. Happy coding!