I am trying to get a basic email usage report. We need to get user names and the size of their email boxes. The code provided below throws an exception
"<HttpError 400 when requesting https://admin.googleapis.com/admin/directory/v1/users?alt=json returned "Bad Request". Details: "[{'message': 'Bad Request', 'domain': 'global', 'reason': 'badRequest'}]">**" on the line
users = service.users().list().execute()
The entire code is provided below:
from __future__ import print_function
import os.path
import csv
import io
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# If modifying these scopes, delete the file token.json.
#SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']
SCOPES = ['https://admin.googleapis.com/admin/directory/v1/users']
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)
print('Getting users in the domain')
users = service.users().list().execute()
# Create a dictionary to store the user data.
user_data = {}
# Iterate over the list of users and get their first name, last name, and mailbox size.
for user in users["users"]:
user_data[user["primaryEmail"]] = {
"firstName": user["name"]["givenName"],
"lastName": user["name"]["familyName"],
"mailboxSize": user["storage"]["quotaUsage"],
}
# Open the CSV file for writing.
with open("user_data.csv", "w", newline="") as f:
writer = csv.writer(f)
# Write the header row.
writer.writerow(["email", "firstName", "lastName", "mailboxSize"])
# Iterate over the user data and write each user's data to a new row in the CSV file.
for email, data in user_data.items():
writer.writerow([email, data["firstName"], data["lastName"], data["mailboxSize"]])
# Close the CSV file.
f.close()
The credentials are correct. Tested multiple times. As you can see from the sample I tried using different scopes. What I am doing wrong here?
You’re missing your
customer='my_customer':