I am trying to use a service account to view and access Shared Drives using the Google API.
I using PHP with the google/apiclient
version v2.16.0
library to access the API.
Here is my code example:
$client = new GoogleClient();
$client->setApplicationName('My App');
$client->setAuthConfig(<contents of $jsonKey file>);
$client->setScopes([
GoogleServiceDrive::DRIVE,
GoogleServiceDrive::DRIVE_APPDATA,
GoogleServiceDrive::DRIVE_FILE,
GoogleServiceDrive::DRIVE_METADATA
]);
$service = new GoogleServiceDrive($client);
$optParams = [
'useDomainAdminAccess' => true,
'q' => 'name contains Clients',
];
$result1 = $service->drives->listDrives();
$result2 = $service->drives->listDrives($optParams);
$result1
returns the following:
GoogleServiceDriveDriveList Object
(
[internal_gapi_mappings:protected] => Array
(
)
[modelData:protected] => Array
(
)
[processed:protected] => Array
(
)
[collection_key:protected] => drives
[drivesType:protected] => GoogleServiceDriveDrive
[drivesDataType:protected] => array
[kind] => drive#driveList
[nextPageToken] =>
[drives] => Array
(
)
)
The list empty since this is a service account, but confirms that authentication is working properly.
$result2
returns an error:
{
"error": {
"code": 400,
"message": "Invalid Value",
"errors": [
{
"message": "Invalid Value",
"domain": "global",
"reason": "invalid",
"location": "q",
"locationType": "parameter"
}
]
}
}
I have tried many different types of strings for the 'q'
parameter, but I always get an invalid value. I have also tried omitting the query parameter and just passing the useDomainAdminAccess
parameter, but that returns the same error.
Despite many hours of searching I cannot figure out why I am getting this error.
Any and all help will be greatly appreciated.
2
Answers
I discovered that the error was originating due to mismatch in scopes given to the Service Account and set in the Client.
The Service Account scopes enabled in the Admin Console had only the following permission:
https://www.googleapis.com/auth/drive
which in PHP Library is equivalent to
GoogleServiceDrive::DRIVE
When I removed the other scopes, the query function worked as documented.
Seems that the Google API and/or PHP Client Library do not generate the proper error message when there is a scope mismatch. Instead, the
Invalid value
error caused a lot of wasted hours on research and troubleshooting.In your showing query, it is required to enclose
Clients
by single or double quotes. So, please modify it as follows and test it again.From:
To:
or
By the way, in this search query, the files included in the trash box are also searched. If you want to avoid this, please add
trashed=false
to the search query likename contains 'Clients' and trashed=false
.Note:
$service
can use "Method: files.list" of Drive API. Please be careful about this.