I began following the code sample given on googleapis github page to help me understand how the Email audit API works.

The sample initialized the API service like this:

from googleapiclient import sample_tools

service, flags = sample_tools.init(
    argv,
    "audit",
    "v1",
    __doc__,
    __file__,
    scope="https://www.googleapis.com/auth/apps/reporting/audit.readonly",
)

Since for my purposes, I'll need read AND write permissions, I included the scope as 'https://www.googleapis.com/auth/apps/reporting/audit'

Here's how I am trying to initialize the service:

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
import os

SCOPES = [
        'https://www.googleapis.com/auth/apps.reporting.audit'
    ]

creds = None

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())

#now attempting to initialize the audit service

auditService = build('audit', 'v1', credentials=creds)

Now, I am facing two issues here:

  • I can't access the given scope After I am prompted to authorize the scopes by logging in to my admin account, I am shown the following message:

Authorization Error Error 400: invalid_scope Some requested scopes cannot be shown: [https://www.googleapis.com/auth/apps.reporting.audit]

  • For testing, if I only request readonly scopes, I get:

googleapiclient.errors.UnknownApiNameOrVersion: name: audit version: v1

Can someone please guide me through how to properly set up an email monitor using googleapis python client? (Is the given sample on github outdated?)

1

There are 1 best solutions below

0
On

The sample code mentioned actually refers to the (now deprecated) Enterprise Activity API. This service was moved to Reports API and as Enterprise Activity API, it is only available for Workspace domains.

So indeed, this script is outdated. If you want to use Reports API to manage Activities, you may want to refer to the python quickstart here.

The end goal of your script is unclear, however as you’ve mentioned you’d like to use Email Audit API, I’d recommend following this guide to confirm if this is the right API for your demand. Keep in mind that this API is also only available for Workspace Domains.

Alternatively, I’d also recommend having a look at GMail API capabilities to see if it fits your needs.