google-apigoogle-api-php-client

Get file name from id with Google Drive PHP Library


I'm using the Google PHP Library with a service account and I'm trying to get the name of a document in a shared team drive by using the document ID. The service account is a content manager on the shared drive. The code below results in code 404, File not found.

PHP Code

$client = new \Google_Client();
$client->setApplicationName('Google API Test');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAccessType('offline');
$client->setAuthConfig('credentials.json);

$service = new \Google_Service_Drive($client); 

$files = $service->files->get('xxxxxxxxxxxxxxxxxxxxxxxxxxx');

echo "File Name: " . $file->getName();

Full Error Message

PHP Fatal error:  Uncaught Google\Service\Exception: {
  "error": {
    "code": 404,
    "message": "File not found: xxxxxxxxxxxxxxxxxxxxxxxxxxx.",
    "errors": [
      {
        "message": "File not found: xxxxxxxxxxxxxxxxxxxxxxxxxxx.",
        "domain": "global",
        "reason": "notFound",
        "location": "fileId",
        "locationType": "parameter"
      }
    ]
  }
}

Solution

  • Because the file was located in a shared drive the supportsAllDrives query parameter needs to be included in the get function.

    $file = $service->files->get($file_id, ['supportsAllDrives' => true]);