Google Admin Directory API - Send a query via apiclient

260 Views Asked by At

I am retrieving a ChromeOS device MAC address via the Google Admin Directory API using the device's Serial Number as reference, and am making my calls through apiclient.

service = discovery.build('admin', 'directory_v1', developerKey=settings.API_KEY)

Here are the calls available for ChromeOS devices; my issue is that I require a Device ID in order to execute the following:

service.chromeosdevices().get(customerId=settings.CID, deviceId=obtained_id, projection=None).execute()

I can send a GET query via the following format:

https://www.googleapis.com/admin/directory/v1/customer/my_customer/devices/chromeos?projection=full&query=id:" + serial + "&orderBy=status&sortOrder=ascending&maxResults=10", "GET")

... but I'm trying to avoid using OAuth2 and just use my API key. Passing the key in a GET request doesn't work either, as it still returns a "Login Required" notice.

How do I squeeze the above query into an apiclient-friendly format? The only option I found via the above calls was to request every device we have (via list), then sift through the mountain of data for the matching Serial number, which seems silly and excessive.

I did notice I could call apiclient.http.HttpRequests, but I couldn't find a way to pass the API key through it either. There's new_batch_http_request, but I can't discern from the docs how to simply pass a URL to it.

Thank you!

1

There are 1 best solutions below

0
On

Got it!

You can't use just a key for Directory API queries, you need a Service account.

I'm using google-auth (see here) since oauth2client is deprecated.

You also need to:

  • Delegate the necessary permissions for your service account (mine has the role of Viewer and has scope access to https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly)

  • Delegate API access to it separately in the Admin Console (Security -> Advanced Settings -> Authentication)

  • Get your json client secret key and place it with your app (don't include it in your VCS)

Obtain your credentials like this:

credentials = service_account.Credentials.from_service_account_file(
    settings.CLIENT_KEY,
    scopes=settings.SCOPES,
    subject=settings.ADMIN_USER)

where ADMIN_USER is the email address of an authorized Domain admin.

Then you send a GET request like so:

authed_session = AuthorizedSession(credentials)
response = authed_session.get(request_id_url)

This returns a Requests object you can read via response.content.

Hope it helps someone else!